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

标签 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
}

但这当然是不合法的。我觉得我在这里缺少一些基本的东西:)

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

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

最佳答案

为什么不使用“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");
}

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

关于c# - 根据 T 返回具有不同内容的 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16836012/

相关文章:

c# - 从单个类公开不同的接口(interface)

c# - 转换字符串值的速记

c# - 如何从 ASP.Net 以 "fire and forget"方式调用 Web 服务

c#: 在列表中找不到对象

c# - 使用泛型接口(interface)的 WCF RESTful 服务

使用泛型从 Swift 到 Kotlin : Protocol to Interface,

c# - System.InvalidCastException double 字符串

c# - 让 ServiceStack 示例工作

kotlin - kotlin 泛型中 <out Any?> 和 <*> 的区别

c# - 如何将 sortedDictionary 转换为 Dictionary?