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

后端 未结 13 2359
-上瘾入骨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条回答
  •  忘掉有多难
    2020-11-22 17:41

    It's Easy.

    Example from MSDN:

    public static void Main()
    {
        // Use the file name to load the assembly into the current
        // application domain.
        Assembly a = Assembly.Load("example");
        // Get the type to use.
        Type myType = a.GetType("Example");
        // Get the method to call.
        MethodInfo myMethod = myType.GetMethod("MethodA");
        // Create an instance.
        object obj = Activator.CreateInstance(myType);
        // Execute the method.
        myMethod.Invoke(obj, null);
    }
    

    Here's a reference link

    https://msdn.microsoft.com/en-us/library/25y1ya39.aspx

提交回复
热议问题