根据T返回具有不同内容的List <T>

pin*_*mer 4 c# generics

我想做这样的事情:

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
}
Run Code Online (Sandbox Code Playgroud)

但那当然不合法.我觉得我错过了一些基本的东西:)

在我的例子中,我从Entity Framework获取不同类型对象的列表,但我的其余逻辑并不依赖于实际类型.它可以在List上工作,也可以是通用的.

GetList()将作为类型参数调用的所有Ts将从相同的基类继承,如果它有所不同.

L-F*_*our 6

为什么不使用'new'运算符来实例化类型:

public List<T> GetList<T>() where T : new()
{
    if (typeof(T) == typeof(Type1)) 
    { 
        return new List<T>() { new T() }; 
    }                     
    // etc...
    throw new Exception("Unknown T");
}
Run Code Online (Sandbox Code Playgroud)

您所要做的就是确保可以通过添加new()约束来实例化您的类型.