What's the best way to instantiate a generic from its name?

前端 未结 3 1386

Assuming I have only the class name of a generic as a string in the form of \"MyCustomGenericCollection(of MyCustomObjectClass)\" and don\'t know the assembly it comes from,

3条回答
  •  猫巷女王i
    2021-01-20 07:43

    If you don't mind translating to VB.NET, something like this should work

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

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题