如何在运行时加载程序集并创建类实例?

Pan*_*kaj 18 c# reflection dll load assemblies

我有一个集会.在这个程序集中,我有一个类和接口.我需要在运行时加载这个程序集,并希望创建该类的对象,并且还想使用该接口.

Assembly MyDALL = Assembly.Load("DALL"); // DALL is name of my dll
Type MyLoadClass = MyDALL.GetType("DALL.LoadClass"); // LoadClass is my class
object obj = Activator.CreateInstance(MyLoadClass);
Run Code Online (Sandbox Code Playgroud)

这是我的代码.怎么可以改进?

Meh*_*hin 20

如果程序集在GAC或bin中,请使用类型名称末尾的程序集名称而不是Assembly.Load().

object obj = Activator.CreateInstance(Type.GetType("DALL.LoadClass, DALL", true));
Run Code Online (Sandbox Code Playgroud)


Sas*_*.R. 12

您应该使用动态方法进行改进.它比反射更快..

以下是使用Dynamic Method创建Object的示例代码.

public class ObjectCreateMethod
{
    delegate object MethodInvoker();
    MethodInvoker methodHandler = null;

    public ObjectCreateMethod(Type type)
    {
        CreateMethod(type.GetConstructor(Type.EmptyTypes));
    }

    public ObjectCreateMethod(ConstructorInfo target)
    {
        CreateMethod(target);
    }

    void CreateMethod(ConstructorInfo target)
    {
        DynamicMethod dynamic = new DynamicMethod(string.Empty,
                    typeof(object),
                    new Type[0],
                    target.DeclaringType);
        ILGenerator il = dynamic.GetILGenerator();
        il.DeclareLocal(target.DeclaringType);
        il.Emit(OpCodes.Newobj, target);
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Ret);

        methodHandler = (MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker));
    }

    public object CreateInstance()
    {
        return methodHandler();
    }
}

//Use Above class for Object Creation.
ObjectCreateMethod inv = new ObjectCreateMethod(type); //Specify Type
Object obj= inv.CreateInstance();
Run Code Online (Sandbox Code Playgroud)

此方法仅需要Activator所需的1/10.

查看http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx