我有一个像这样的通用函数:
public List<T> DoStuff<T>(){
if(typeof(T) == typeOf(ClassA))
return CreateListWithTypeA();
if(typeof(T) == typeOf(ClassB))
return CreateListWithTypeB();
}
这里的助手:
public List<ClassA> CreateListWithTypeA(){
return new List<ClassA>();
}
public List<ClassA> CreateListWithTypeB(){
return new List<ClassA>();
}
DoStuff()中的错误:
Cannot convert type System.Collection.Generic.List<ClassA> to System.Collection.Generic.List<T>
PS:ClassA和ClassB实现接口。不确定这是否有帮助
答案 0 :(得分:4)
我认为这不是泛型的很好用,因为它限制T
仅是两种类型之一。
但是,如果您坚持要这样做,则可以通过以下方法来解决问题:
public static List<T> GetList<T>() where T : YourInterface { // The constraint here provides just a *bit* more compile time checking
if (typeof(T) == typeof(A)) {
return CreateListWithTypeA().Cast<T>().ToList();
}
// other cases here...
throw new Exception("T is not the right type!");
}
答案 1 :(得分:3)
您总是可以这样做,但这是非常多余的
public List<T> DoStuff<T>()
{
return new List<T>();
}
假设这些助手中还有更多的事情
public List<T> CreateListWithTypeA<T>(){
return new List<T>();
}
...
如果您需要访问特定于界面的内容,请使用约束条件
where T : IMyLovelyHorse
如果您需要自己重新创建T
,请添加new()
约束
where T : new()
最后,在通用方法中使用if(typeof(T) == typeOf(ClassA))
模式通常会指出某些错误,需要考虑一些不同的事物,尽管通常是