I found this http://blogs.msdn.com/haibo_luo/archive/2005/11/17/494009.aspx但尝试使用它但失败了。
如何使用反射创建对象并通过将其放入委托中来使其快速?
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 之前,我尝试至少调用它,当我执行上述操作时,我收到错误
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
附加信息:调用目标已引发异常。
如果我调用 d() 相反,我会得到异常
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Type must derive from Delegate.
如何将无参数构造函数放入委托中并调用它?
如果您有权访问 .NET 3.5(您使用的Func<T>
建议),你可能会发现Expression
比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();
}
很容易扩展它以使用特定的构造函数、传递参数或添加构造函数后属性绑定;强制转换、转换等(参见这个相关答案 https://stackoverflow.com/questions/2044371/2044434#2044434)。如果您有特定的场景,我很乐意添加一个示例。
另请注意,您应该缓存并重用任何此类构造函数 - 否则您将失去好处(即不要在每次调用时重新创建委托)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)