Can I load a .NET assembly at runtime and instanti

2019-01-01 02:52发布

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 implements a interface, so once I instantiate the class, I will then cast it to the interface.

Assembly name:

library.dll

Type name:

Company.Project.Classname


EDIT: I dont have the absolute path of the DLL, so Assembly.LoadFile won't work. The DLL might be in the application root, system32, or even loaded in the GAC.

标签: c# assemblies
13条回答
美炸的是我
2楼-- · 2019-01-01 03:51

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);
}
查看更多
登录 后发表回答