【问题标题】:Generate constructor that takes itself in constructor with TypeBuilder使用 TypeBuilder 生成将自身置于构造函数中的构造函数
【发布时间】:2020-03-12 05:33:34
【问题描述】:

我最近开始使用 Typebuilder,我希望创建一个构造函数来接受我目前正在构建的类型。

在代码中你可以写如下:

public class Foo 
{
    public Foo(Foo fooToCopy) 
    {
        // Do copy code here
    }
}

我想不出一种方法可以在构建时引用正在构建的类型。我尝试过早地创建类型以便在指定构造函数时能够引用它,但是一旦构造完成,我就无法继续编辑类型。

我有什么方法可以使用 TypeBuilder 来完成这项工作吗?

【问题讨论】:

    标签: c# reflection reflection.emit typebuilder


    【解决方案1】:

    TypeBuilder 继承 Type,因此您可以在任何想要引用正在构建的类型的地方提供构建器本身:

    var ctor = typeBuilder.DefineConstructor(
      MethodAttributes.Public,
      CallingConventions.Standard, 
      new Type[] { typeBuilder }
    );
    

    【讨论】:

    • 你说的好像很简单!我可以确认这符合我的需要,因此我已将您的回复标记为已接受的答案。感谢您的快速回复!
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2016-12-16
    • 2012-03-08
    • 2011-08-21
    • 1970-01-01
    • 2016-12-07
    • 2012-06-30
    • 2018-07-21
    相关资源
    最近更新 更多