這裏有兩種方式:
- 使用仿製藥,並共同基類
- 使用接口
方法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