是否可以发出从泛型类型派生的类型,同时将其自身指定为泛型类型参数?
想象一下以下完全合法的类型层次结构:
class A<T> where T : A<T>
{
}
class B : A<B>
{
public B():base(){}
}
我的问题给出了 A<> 的静态编译定义。是否可以动态发出 B 类型?
问题是如何在ModuleBuilder.DefineType
中指定父类型。
或者也许还有另一种方法来生成这样的类型,除了
- 使用上述使用 CodeDom 的方法
- (这很像创建一个临时文件并将其传递给 csc.exe :-))
编辑: 类型 B
应该具有显式公共默认构造函数,调用从 A
继承的默认构造函数。
Imagine the following perfectly legal type hierarchy:
class A<T> where T : A<T>
{
}
class B : A<B>
{
public B():base(){}
}
My question is given a statically compiled definition of A<> is it possible to emit the type B dynamically?
The problem is how to specify the parent type in ModuleBuilder.DefineType
.
Or maybe there is another way to produce such a type, other than
- using the aforementioned method
- using CodeDom (which is much like creating a temporary file and passing it to csc.exe :-))
EDIT:
The type B
should have explicit public default constructor invoking the default constructor inherited from A<B>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用不指定父类型的
ModuleBuilder.DefineType
重载,然后使用TypeBuilder.SetParent
方法将父类型设置为递归类型(使用类似typeof(A<>).MakeGenericType(tb)
的参数,其中tb
是您的TypeBuilder
,但我没有我面前的 C# 编译器)。编辑 - 这是一个工作示例,假设您有一个
ModuleBuilder mb
。对于空的默认构造函数,您根本不需要使用DefineConstructor
方法;或者您可以使用DefineDefaultConstructor
。不过,我提供了一个显式调用基本构造函数的示例,以防您想要在其中添加一些额外的逻辑。You can use an overload of
ModuleBuilder.DefineType
which doesn't specify a parent type, and then use theTypeBuilder.SetParent
method to set the parent to the recursive type (using an argument something liketypeof(A<>).MakeGenericType(tb)
wheretb
is yourTypeBuilder
, but I don't have a C# compiler in front of me).EDIT - here's a working example, assuming you've got a
ModuleBuilder mb
. For an empty default constructor, you don't need to use theDefineConstructor
method at all; alternatively you could useDefineDefaultConstructor
. I've included an example where the base constructor is explicitly called, though, in case you have some extra logic you want to add in there.