简体   繁体   English

创建通用列表<T>带反射

[英]Create generic List<T> with reflection

I have a class with a property IEnumerable<T> .我有一个属性IEnumerable<T> How do I make a generic method that creates a new List<T> and assigns that property?如何创建一个创建新List<T>并分配该属性的通用方法?

IList list = property.PropertyType.GetGenericTypeDefinition()
    .MakeGenericType(property.PropertyType.GetGenericArguments())
    .GetConstructor(Type.EmptyTypes);

I dont know where is T type can be anything我不知道T型在哪里可以是任何东西

Assuming you know the property name, and you know it is an IEnumerable<T> then this function will set it to a list of corresponding type:假设您知道属性名称,并且您知道它是一个IEnumerable<T>那么此函数会将其设置为相应类型的列表:

public void AssignListProperty(Object obj, String propName)
{
  var prop = obj.GetType().GetProperty(propName);
  var listType = typeof(List<>);
  var genericArgs = prop.PropertyType.GetGenericArguments();
  var concreteType = listType.MakeGenericType(genericArgs);
  var newList = Activator.CreateInstance(concreteType);
  prop.SetValue(obj, newList);
}

Please note this method does no type checking, or error handling.请注意,此方法不进行类型检查或错误处理。 I leave that as an exercise to the user.我把它留给用户作为练习。

using System;
using System.Collections.Generic;

namespace ConsoleApplication16
{
    class Program
    {
        static IEnumerable<int> Func()
        {
            yield return 1;
            yield return 2;
            yield return 3;
        }

        static List<int> MakeList()
        {
            return (List<int>)Activator.CreateInstance(typeof(List<int>), Func());
        }

        static void Main(string[] args)
        {
            foreach(int i in MakeList())
            {
                Console.WriteLine(i);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM