【问题标题】:What's the best way to instantiate a generic from its name?从其名称实例化泛型的最佳方法是什么?
【发布时间】:2008-09-24 21:55:38
【问题描述】:

假设我只有一个泛型的类名作为“MyCustomGenericCollection(of MyCustomObjectClass)”形式的字符串,并且不知道它来自哪个程序集,那么创建该对象实例的最简单方法是什么?

如果有帮助,我知道该类实现了 IMyCustomInterface 并且来自加载到当前 AppDomain 的程序集。

Markus Olsson 给出了一个很好的例子 here,但我不知道如何将它应用于泛型。

【问题讨论】:

    标签: .net vb.net generics reflection .net-2.0


    【解决方案1】:

    解析后,使用Type.GetType(string) 获取对所涉及类型的引用,然后使用Type.MakeGenericType(Type[]) 构造您需要的特定泛型类型。然后,使用Type.GetConstructor(Type[]) 获取对特定泛型类型的构造函数的引用,最后调用ConstructorInfo.Invoke 获取对象的实例。

    Type t1 = Type.GetType("MyCustomGenericCollection");
    Type t2 = Type.GetType("MyCustomObjectClass");
    Type t3 = t1.MakeGenericType(new Type[] { t2 });
    ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);
    object obj = ci.Invoke(null);
    

    【讨论】:

      【解决方案2】:

      MSDN 文章How to: Examine and Instantiate Generic Types with Reflection 描述了如何使用反射来创建泛型类型的实例。将其与 Marksus 的示例结合使用有望帮助您入门。

      【讨论】:

        【解决方案3】:

        如果你不介意翻译成 VB.NET,这样的东西应该可以工作

        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            // find the type of the item
            Type itemType = assembly.GetType("MyCustomObjectClass", false);
            // if we didnt find it, go to the next assembly
            if (itemType == null)
            {
                continue;
            }
            // Now create a generic type for the collection
            Type colType = assembly.GetType("MyCusomgGenericCollection").MakeGenericType(itemType);;
        
            IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType);
            break;
        }
        

        【讨论】:

          猜你喜欢
          • 2010-11-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-01
          • 1970-01-01
          • 2014-10-15
          • 2010-09-06
          • 1970-01-01
          相关资源
          最近更新 更多