Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

后端 未结 13 2305
-上瘾入骨i
-上瘾入骨i 2020-11-22 17:21

Is it possible to instantiate an object at runtime if I only have the DLL name and the class name, without adding a reference to the assembly in the project? The class imple

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 17:55

    Yes. You need to use Assembly.LoadFrom to load the assembly into memory, then you can use Activator.CreateInstance to create an instance of your preferred type. You'll need to look the type up first using reflection. Here is a simple example:

    Assembly assembly = Assembly.LoadFrom("MyNice.dll");
    
    Type type = assembly.GetType("MyType");
    
    object instanceOfMyType = Activator.CreateInstance(type);
    

    Update

    When you have the assembly file name and the type name, you can use Activator.CreateInstance(assemblyName, typeName) to ask the .NET type resolution to resolve that into a type. You could wrap that with a try/catch so that if it fails, you can perform a search of directories where you may specifically store additional assemblies that otherwise might not be searched. This would use the preceding method at that point.

提交回复
热议问题