我有个集会。在这个程序集中,我有一个类和一个接口。我需要在运行时加载这个程序集,并希望创建该类的一个对象,还希望使用该接口。
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);这是我的代码。如何改进呢?
发布于 2009-11-26 22:11:40
如果您的程序集在GAC或bin中,请在类型名称的末尾使用程序集名称,而不是Assembly.Load()。
object obj = Activator.CreateInstance(Type.GetType("DALL.LoadClass, DALL", true));发布于 2009-11-27 04:57:56
你应该使用动态的方法来改进。它比反射更快..
下面是使用动态方法创建对象的示例代码。
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();这种方法只需要Activator所需时间的1/10。
查看http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx
发布于 2013-05-25 06:13:54
查看http://www.youtube.com/watch?v=x-KK7bmo1AM,修改他的代码以加载多个程序集
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string assemblyName = args.Name.Split(',').First();
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace." + assemblyName + ".dll"))
{
byte[] assemblyData = new byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}在你的main方法中放入
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;请确保将程序集添加到项目中,并将生成操作属性更改为"Embedded Resource“。
https://stackoverflow.com/questions/1803540
复制相似问题