C# 创建通用列表<;T>;深思熟虑

C# 创建通用列表<;T>;深思熟虑,c#,reflection,C#,Reflection,我有一个属性为IEnumerable的类。如何创建一个通用方法来创建一个新的列表,并分配该属性 IList list = property.PropertyType.GetGenericTypeDefinition() .MakeGenericType(property.PropertyType.GetGenericArguments()) .GetConstructor(Type.EmptyTypes); 我不知道在哪里T类型可以是任何东西假设您知道属性名称,并且您知道它是I

我有一个属性为
IEnumerable
的类。如何创建一个通用方法来创建一个新的
列表
,并分配该属性

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

我不知道在哪里
T
类型可以是任何东西假设您知道属性名称,并且您知道它是
IEnumerable
,则此函数将其设置为相应类型的列表:

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);
}
public void AssignListProperty(Object obj,String propName)
{
var prop=obj.GetType().GetProperty(propName);
var listType=类型(列表);
var genericArgs=prop.PropertyType.GetGenericArguments();
var-concreteType=listType.MakeGenericType(genericArgs);
var newList=Activator.CreateInstance(concreteType);
属性设置值(对象,新列表);
}
请注意,此方法不进行类型检查或错误处理。我将此作为练习留给用户。

使用系统;
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);
            }
        }
    }
}
使用System.Collections.Generic; 命名空间控制台应用程序16 { 班级计划 { 静态IEnumerable Func() { 收益率1; 收益率2; 收益率3; } 静态列表生成列表() { return(List)Activator.CreateInstance(typeof(List),Func()); } 静态void Main(字符串[]参数) { foreach(生成列表()中的int i) { 控制台写入线(i); } } } }
不确定你的意思,你能不能不使用
IEnumerable.ToList()
你到底想做什么,创建一个
列表
表单
IEnumerable
?我需要创建一个类型为property@rkmax-请查看我的更新答案。为什么不直接使用
Func().ToList()
T在哪里?不是泛型。我完全忘记了Activator.CreateInstance,错误处理已完成;)