【问题标题】:how to create a list of type obtained from reflection如何创建从反射获得的类型列表
【发布时间】:2014-02-02 17:01:02
【问题描述】:

我的代码如下所示:

Assembly assembly = Assembly.LoadFrom("ReflectionTest.dll");
Type myType = assembly.GetType(@"ReflectionTest.TestObject");
var x = Convert.ChangeType((object)t, myType);   

//List<myType> myList = new List<myType>();
//myList.Add(x);

代码的注释部分是我卡住的地方。我从服务中获取了一些对象,并且转换也可以正常工作。我正在尝试填充此类对象的列表,稍后将绑定到 WPF DataGrid。

任何帮助表示赞赏!

【问题讨论】:

    标签: c# list c#-4.0 reflection wpfdatagrid


    【解决方案1】:
    var listType = typeof(List<>).MakeGenericType(myType)
    var list = Activator.CreateInstance(listType);
    
    var addMethod = listType.GetMethod("Add");
    addMethod.Invoke(list, new object[] { x });
    

    您也许可以转换为IList 并直接调用Add,而不是使用反射查找方法:

    var list = (IList)Activator.CreateInstance(listType);
    list.Add(x);
    

    【讨论】:

      【解决方案2】:

      试试这个:

      var listType = typeof(List<>);
      var constructedListType = listType.MakeGenericType(myType);
      
      var myList = (IList)Activator.CreateInstance(constructedListType);
      myList.Add(x);
      

      列表不会是强类型的,但您可以将项目添加为对象。

      【讨论】:

        【解决方案3】:

        你需要MakeGenericType方法:

        var argument = new Type[] { typeof(myType) };
        var listType = typeof(List<>); 
        var genericType = listType.MakeGenericType(argument); // create generic type
        var instance = Activator.CreateInstance(genericType);  // create generic List instance
        
        var method = listType.GetMethod("Add"); // get Add method
        method.Invoke(instance, new [] { argument }); // invoke add method 
        

        或者,您可以将您的实例转换为IList 并直接使用Add 方法。或者使用dynamic 输入而不必担心转换:

        dynamic list = Activator.CreateInstance(genericType);
        list.Add("bla bla bla...");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-13
          • 2021-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-29
          • 2013-09-15
          • 1970-01-01
          相关资源
          最近更新 更多