【问题标题】:Create list of variable type创建变量类型列表
【发布时间】:2010-03-22 14:59:00
【问题描述】:

我正在尝试创建某种类型的列表。

我想使用 List 表示法,但我只知道“System.Type”

a 拥有的类型是可变的。如何创建变量类型列表?

我想要类似这段代码的东西。

public IList createListOfMyType(Type myType)
{
     return new List<myType>();
}

【问题讨论】:

  • 确保没有错误的设计,因为这很臭。

标签: c# list


【解决方案1】:

这样的事情应该可以工作。

public IList createList(Type myType)
{
    Type genericListType = typeof(List<>).MakeGenericType(myType);
    return (IList)Activator.CreateInstance(genericListType);
}

【讨论】:

  • 在我让它工作之前,我不得不摆弄一下这个。我完全是使用 Type 的新手,所以这里有一个代码 sn-p 其他人可能会发现在您从 Main 或其他方法调用此 createList 方法时会有所帮助: string[] words = {"stuff", "things" , "wordz", "misc"}; var shtuff = createList(words.GetType());
  • 我知道这是旧的,但是@Jan,它解决了你的问题,它应该被标记为答案。 @kayleeFrye_onDeck 你也可以这样做 typeof(string[])
【解决方案2】:

您可以使用反射,这是一个示例:

    Type mytype = typeof (int);

    Type listGenericType = typeof (List<>);

    Type list = listGenericType.MakeGenericType(mytype);

    ConstructorInfo ci = list.GetConstructor(new Type[] {});

    List<int> listInt = (List<int>)ci.Invoke(new object[] {});

【讨论】:

  • 问题是我们不知道 myType 是 typeof(int),所以你最后的语句不能是 List,我们想要像 Liar 这样的东西,但是当然是做不到的。要创建实例,我们应该使用 System.Activator.CreateInstance(myType)。但话又说回来,如果是 myType 类型的对象,则返回值。您必须使用 System.Type 来了解方法/属性/接口等。
  • 可以使用泛型来完成:List CreateMyList()。在这个方法里面你可以做: Type myType = typeof(T);然后一切如上。您将能够使用这样的方法: List list = CreateList()
  • 投反对票,因为该解决方案不适合该问题。问题是 'T' 未知,因此即使执行 CreateMyList 也是无效的,因为 T 很可能不可用。
【解决方案3】:

谢谢!这是一个很大的帮助。这是我对实体框架的实现:

    public System.Collections.IList TableData(string tableName, ref IList<string> errors)
    {
        System.Collections.IList results = null;

        using (CRMEntities db = new CRMEntities())
        {
            Type T = db.GetType().GetProperties().Where(w => w.PropertyType.IsGenericType && w.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Entity.DbSet<>)).Select(s => s.PropertyType.GetGenericArguments()[0]).FirstOrDefault(f => f.Name == tableName);
            try
            {
                results = Utils.CreateList(T);
                if (T != null)
                {
                    IQueryable qrySet = db.Set(T).AsQueryable();
                    foreach (var entry in qrySet)
                    {
                        results.Add(entry);
                    }
                }
            }
            catch (Exception ex)
            {
                errors = Utils.ReadException(ex);
            }
        }

        return results;
    }

    public static System.Collections.IList CreateList(Type myType)
    {
        Type genericListType = typeof(List<>).MakeGenericType(myType);
        return (System.Collections.IList)Activator.CreateInstance(genericListType);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 2015-01-07
    • 2012-08-30
    • 1970-01-01
    • 2012-08-30
    • 2020-05-10
    相关资源
    最近更新 更多