Seb*_*ebi 0 c# generics generic-list
我有一个接口和两个类.
public interface IMyInterface { }
public class A : IMyInterface { }
public class B : IMyInterface { }
Run Code Online (Sandbox Code Playgroud)
我有一个通用的方法,
private List<T> GetList<T>(DataTable table)
where T : class, IMyInterface
{
...
}
Run Code Online (Sandbox Code Playgroud)
应该根据DataTable中的数据返回一个对象列表.所以,我在这个方法中创建了一个列表,我想在最后返回.我以为我可以做到以下几点,
private List<T> GetList<T>(DataTable table)
where T : class, IMyInterface
{
List<T> myList = new List<T>;
// Now I thought I could easily add Objects based on T because,
// both classes implement the interface
if (typeof(T) == typeof(B))
{
myList.Add(new B());
}
else
{
myList.Add(new A());
}
return myList;
}
Run Code Online (Sandbox Code Playgroud)
但编译器告诉我"参数类型A(B)不是可以指定的"!为什么不可分配?
好吧,或者我可以做以下事情,
private List<T> GetList<T>(DataTable table)
where T : class, IMyInterface
{
List<IMyInterface> myList = new List<IMyInterface>;
// Now I can assign the Object's :)
if (typeof(T) == typeof(B))
{
myList.Add(new B());
}
else
{
myList.Add(new A());
}
return myList as List<T>;
}
Run Code Online (Sandbox Code Playgroud)
编译器没有抱怨,但return子句的结果始终为null.肯定有值myList.演员似乎失败了.有人请帮我更优雅地解决这个问题.
一种方法是添加new()约束.限制是您需要类型参数T的公共无参数构造函数.
private static List<T> GetList<T>(DataTable table) where T : class, IMyInterface, new()
{
List<T> myList = new List<T>();
T instance = new T();
//access anything defined in `IMyInterface` here
myList.Add(instance);
return myList;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
995 次 |
| 最近记录: |