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

后端 未结 13 2367
-上瘾入骨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:53

    Activator.CreateInstance ought to work.

    IFace object = (IFace)Activator.CreateInstance( "AssemblyName",
                                                    "TypeName" )
                                   .Unwrap();
    

    Note: The type name must be the fully qualified type.

    Example:

    var aray = (IList)Activator.CreateInstance("mscorlib","System.Collections.ArrayList").Unwrap();
    aray.Add(10);
    
    foreach (object obj in aray)
    {
        Console.WriteLine(obj);
    }
    

提交回复
热议问题