我想要做类似于这样的事情:
public List<T> GetList<T>()
{
if (typeof(T) == typeof(Type1))
{
return new List<Type1>() { new Type1(), new Type1(), new Type1() };
}
if (typeof(T) == typeof(Type2))
{
return new List<Type2>() {new Type2(), new Type2()};
}
throw new Exception("Unknown T");
}
public void DoStuffWithGenericList<T>()
{
var list = GetList<T>();
// do stuff that does not depend on T
}
但那当然是不合法的。我感觉我在这里缺少一些基本的东西 :)
在我的情况下,我从Entity Framework获取了不同类型对象的列表,但我的其他逻辑并不依赖于实际类型。它可以仅使用List或可以是泛型。
所有作为类型参数调用GetList()的T都将继承自相同的基类(如果有区别的话)。
T
的新实例而不对它们施加约束,并且仍然相对快速,那么您可以使用编译的lambda表达式或IL。 - Daniel