如何使用 IL Emit 定义相互引用的两种类型
我需要使用反射 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
TypeBuilder 是 Type 的子类:
MSDN
您可以将其传递给 DefineProperty。
TypeBuilder is a subclass of Type:
MSDN
You can pass it in to DefineProperty.