问题描述
我发现但试图利用它和失败。
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[] { });
把它在一个deleage之前,我想至少调用它,当我在上面做我得到的误差
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).
这篇关于使用委托调用构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!