加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用Delegate调用构造函数

发布时间:2020-12-15 18:07:08 所属栏目:百科 来源:网络整理
导读:我找到了 this,但试图使用它并失败了. 如何使用反射创建对象并通过将其置于委托中来加快速度? DynamicMethod dm = new DynamicMethod("MyCtor",t,new Type[] { }); var ctor = t.GetConstructor(new Type[] { }); ILGenerator ilgen = dm.GetILGenerator();
我找到了 this,但试图使用它并失败了.

如何使用反射创建对象并通过将其置于委托中来加快速度?

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[] { });

在把它删除之前我试图至少调用它,当我在上面做的时候我得到了错误

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();        
}

很容易扩展它以使用特定的构造函数,传递参数或添加post-constructor属性绑定;演员,转换等(见this related answer).如果你有一个特定的场景,我会很乐意添加一个例子.

另请注意,您应该缓存并重新使用任何此类构造函数 – 否则您将失去优势(即不要重新创建每次调用的委托).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读