这里有两种方式:
- 使用仿制药,并共同基类
- 使用接口
方法1:
public class BaseClass
{
public int SomeProperty { get; set; }
}
public class MyType : BaseClass { }
public class MyOtherType : BaseClass { }
public class ClassWithMethod
{
public static List<T> DoSomethingSimple<T>(List<T> myTypes)
where T : BaseClass
{
return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList();
}
}
方法2:
public interface ICommon
{
int SomeProperty { get; set; }
}
public class MyType : ICommon
{
public int SomeProperty { get; set; }
}
public class MyOtherType : ICommon
{
public int SomeProperty { get; set; }
}
public class ClassWithMethod
{
public static List<T> DoSomethingSimple<T>(List<T> myTypes)
where T : ICommon
{
return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList();
}
}
现在,如果你尝试使该方法直接使用界面,如下所示:
public class ClassWithMethod
{
public static List<ICommon> DoSomethingSimple(List<ICommon> myTypes)
{
return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList();
}
}
然后,如果您在拨打电话时有List<ICommon>
,那么这将起作用,但如果您有List<MyType>
则无效。
public class ClassWithMethod
{
public static List<ICommon> DoSomethingSimple(IEnumerable<ICommon> myTypes)
{
return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList();
}
}
注意,我改为使用IEnumerable<ICommon>
代替:在C#4.0中,如果我们稍微改变方法可以做到这一点。这里的概念被称为共同和反方差,除此之外我不会多说这些。搜索堆栈溢出以获取有关该主题的更多信息。
提示:我会改变输入参数是IEnumerable<T>
不管,因为这会令你的方法更多的场合下使用,你可以有不同类型的集合,数组等。并且,只要它们含有正确的类型,它们可以传递给方法。通过将自己限制为List<T>
,可以强制代码的用户在某些情况下转换为列表。我的准则在输入参数中应尽可能不明确,并尽可能在输出参数中尽可能具体。
是在这两种情况下从共同基类继承的“SomeProperty”? – 2010-07-29 11:19:03