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

本文关键字:gt 反射 lt 列表 创建 | 更新日期: 2023-09-27 17:59:13

我有一个属性为IEnumerable<T>的类。如何创建一个通用方法来创建一个新的List<T>并分配该属性?

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

我不知道T类型在哪里可以是任何

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

假设您知道属性名称,并且知道它是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);
}

请注意,此方法不进行类型检查或错误处理。我将此作为练习留给用户。

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);
            }
        }
    }
}