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

后端 未结 13 2303
-上瘾入骨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
    2020-11-22 17:48

    Starting from Framework v4.5 you can use Activator.CreateInstanceFrom() to easily instantiate classes within assemblies. The following example shows how to use it and how to call a method passing parameters and getting return value.

        // Assuming moduleFileName contains full or valid relative path to assembly    
        var moduleInstance = Activator.CreateInstanceFrom(moduleFileName, "MyNamespace.MyClass");
        MethodInfo mi = moduleInstance.Unwrap().GetType().GetMethod("MyMethod");
        // Assuming the method returns a boolean and accepts a single string parameter
        bool rc = Convert.ToBoolean(mi.Invoke(moduleInstance.Unwrap(), new object[] { "MyParamValue" } ));
    

提交回复
热议问题