如何使用 IL Emit 定义相互引用的两种类型

发布于 2024-08-19 11:07:17 字数 421 浏览 5 评论 0原文

我需要使用反射 Emit 来定义类似的东西:

public class Foo {
    public Bar Bar { get; set; }
}

public class Bar {
    public Foo Foo { get; set; }
}

困难在于,当调用 TypeBuilder.DefineProperty() 时,我需要传递属性返回值的 System.Type,而该值尚不存在。如果参考文献只采用一种方式,那会很容易,但是采用两种方式就会导致先有鸡还是先有蛋的问题。

我希望找到一个采用 TypeBuilder 而不是 Type 的重载,这将使我能够同时定义两个类,然后在最后对两个类调用 TypeBuilder.CreateType() 。但我没有看到这样的事情。

解决这个问题的正确方法是什么?

I need to define something like this using reflection Emit:

public class Foo {
    public Bar Bar { get; set; }
}

public class Bar {
    public Foo Foo { get; set; }
}

The difficulty is that when calling TypeBuilder.DefineProperty(), I need to pass the System.Type of the property's return value, which doesn't exist yet. If the reference only went one way, it would be easy, but going both ways causes a chicken and egg problem.

I was hoping to find an overload that takes a TypeBuilder instead of a Type, which would let me define both classes at the same time and then call TypeBuilder.CreateType() on both at then end. But I'm not seeing such thing.

What is the right way to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开半夏魅人心 2024-08-26 11:07:17

TypeBuilder 是 Type 的子类:
MSDN

您可以将其传递给 DefineProperty。

TypeBuilder is a subclass of Type:
MSDN

You can pass it in to DefineProperty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文