不同的情況下需要返回不同類型的數據集合,特點是,這些類型都繼承自同一個接口。
public interface IExample { string ID { get; set; } string Name { get; set; } } public class A : IExample { public string ID { get; set; } public string Name { get; set; } } public class B : IExample { public string ID { get; set; } public string Name { get; set; } } public class Test { //方法A public List<T> GetRefList<T>(string key) where T : IExample { if (key == "A") return new List<A>(); else if (key == "B") return new List<A>(); } //方法B public T[] GetRefList<T>(string key) where T : IExample { if (key == "A") return new A[10]; else if (key == "B") return new B[10]; } //方法C public IExample[] GetRefList(string key) { if (key == "A") return new A[10]; else if (key == "B") return new B[10]; else return null; } //方法D public List<IExample> GetRefList(string key) { if (key == "A") return new List<A>(); else if (key == "B") return new List<B>(); else return null; } }
其中,方法A、B、D編譯都不能通過,只有方法C可以編譯通過。
補充一種情況:
//方法E public IEnumerable<IExample> GetRefList(string key) { if (key == "A") return new List<A>(); else if (key == "B") return new B[10]; else return null; }
可以編譯通過。這樣的話,原來存在的問題基本可以解決。
這里的List<IParent>和List<SubChild>之間的相互轉換涉及到泛型的協變和抗變。
.NET4.0對IEnumerable接口的修改?
2.0中的定義:
public interface IEnumerable<T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}4.0中的定義:
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}可以看到4.0中增加了對協變的支持。
可以在兩個版本試下, 下面的語句在2.0下會報錯。
List<SubClass> subarr = new List<SubClass>();
IEnumerable<IParent> parentarr = subarr;
這里參考資料:http://www.cnblogs.com/tenghoo/archive/2012/12/04/interface_covariant_contravariant.html