我收到此扩展方法的以下编译时问题。
error CS1061: 'SomeClass' does not contain a definition for 'SomeProperty' and
no extension method 'SomeProperty' accepting a first argument of type 'SomeClass' could be found (are
you missing a using directive or an assembly reference?)
这些类都在同一个项目中,看来我可以毫无问题地声明该类了。我该如何解决?
using System;
using System.Collections;
using System.Collections.Generic;
public static class SomeClassListEx
{
public static List<SomeClass> SomeMethod<SomeClass>(this IEnumerable<SomeClass> list, int id) // where T : SomeClass
{
List<SomeClass> result = new List<SomeClass> ();
foreach (SomeClass something in list)
{
if(something.SomeProperty.SomeList.Contains(id))
{
result.Add (something);
}
}
return result;
}
}
public abstract class SomeClass : IEquatable<SomeClass>
{
public SomethingElse SomeProperty { get; set; }
}
public interface SomethingElse
{
List<int> SomeList { get; }
}
最佳答案
您将方法设为通用,因此在SomeMethod<SomeClass>
不再是SomeClass
之后,它是一个通用参数,在您实际调用该方法时可以用任何东西替换。
您的扩展方法不应该是通用的:
public static List<SomeClass> SomeMethod(this IEnumerable<SomeClass> list, int id)
{
List<SomeClass> result = new List<SomeClass> ();
foreach (SomeClass something in list)
{
if(something.SomeProperty.SomeList.Contains(id))
{
result.Add (something);
}
}
return result;
}
关于c# - 扩展方法找不到类型的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21866138/