Create generic List with reflection

2020-02-12 09:03发布

I have a class with a property IEnumerable<T>. How do I make a generic method that creates a new List<T> and assigns that property?

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

I dont know where is T type can be anything

标签: c# reflection
2条回答
一纸荒年 Trace。
2楼-- · 2020-02-12 09:12

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:

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.

查看更多
萌系小妹纸
3楼-- · 2020-02-12 09:14
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);
            }
        }
    }
}
查看更多
登录 后发表回答