使用Delegate来调用构造函数 [英] Using a Delegate to call a constructor
问题描述
我发现这个,但试图使用它并且失败。
I found this but tried to use it and failed.
我如何使用反射创建对象,并将其放在委托中快速进行?
How can i create an object using reflections and make it fast by putting it in a delegate?
DynamicMethod dm = new DynamicMethod("MyCtor", t, new Type[] { });
var ctor = t.GetConstructor(new Type[] { });
ILGenerator ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Newobj, ctor);
ilgen.Emit(OpCodes.Ret);
var d = (Func<T>)dm.CreateDelegate(t);
dm.Invoke(null, new object[] { });
在把它放在一个元数据之前,我试图至少调用它,当我上面我得到错误
Before putting it in a deleage i tried to at least invoke it and when i did above i get the error
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
其他信息:调用目标抛出异常。
Additional information: Exception has been thrown by the target of an invocation.
如果我调用d(),我得到异常
If i call d() instead i get the exception
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Type must derive from Delegate.
如何将一个无参数构造函数放入代理并调用?
How do i put a no param constructor into a delegate and call it?
推荐答案
如果您可以访问.NET 3.5(您使用 Func< T>
),您可能会发现表达式
比 ILGenerator
更容易:
If you have access to .NET 3.5 (which your use of Func<T>
suggests), you may find Expression
easier than ILGenerator
:
class Foo { }
static void Main() {
Func<Foo> func = GetCtor<Foo>(); // cache this somewhere!
Foo foo = func();
}
static Func<T> GetCtor<T>() {
Type type = typeof(T);
Expression body = Expression.New(type);
return Expression.Lambda<Func<T>>(body).Compile();
}
很容易扩展,以使用特定的构造函数,传递参数或添加后构造函数属性绑定;转换等等(请参阅此相关答案)。如果你有一个具体的场景,我会很高兴地添加一个例子。
Pretty easy to extend that to use a specific constructor, passing arguments, or adding post-constructor property bindings; casts, conversions, etc (see this related answer). If you have a specific scenario, I'll happily add an example.
还要注意,你应该缓存并重新使用任何这样的构造函数 - 否则你会失去好处即不要重新创建每个呼叫的委托)。
Note also that you should cache and re-use any such constructors - otherwise you lose the benefit (i.e. don't recreate the delegate per-call).
这篇关于使用Delegate来调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!