9

I'm making a .NET-compliant compiler using Reflection.Emit. The problem is, that although TypeBuilder is derived from Type, it does not let me use all the handy methods that Type provides.

The matters that really concern me are:

  1. Is there any way to get a list of methods, fields, properties, constructors etc. defined in a TypeBuilder, or I really have to make a TypeBuilderWrapper that keeps track of all those entities by myself? It has to store them somewhere inside, so there must be some way to extract them?

  2. The GetMethod method is very handy, because it can find the best fitting method override taking inheritance and generic covariance into account. Do I really have to reimplement it myself for the TypeBuilderWrapper?

The same issue probably applies to MethodBuilder, FieldBuilder etc. which, I believe, do not implement the lookup methods of MethodInfo and FieldInfo respectively.

4

1 回答 1

9

TypeBuilder, MethodBuilder, 等是Type, MethodInfo, 但他们没有所有的能力Type,MethodInfo直到你打电话TypeBuilder.CreateType()。原因TypeBuilderType它允许你在构建类的A同时B,你可以在两个方向上引用它们而无需完成它们。让我举个例子:

// sample.x
class A {
    void method1(B b) {}
}

class B {
    void method2(A a) {}
}

所以生成类的 C# 代码AB

// ...
// define classes
TypeBuilder classA = moduleBuilder.DefineType("A");
TypeBuilder classB = moduleBuilder.DefineType("B");

// define class A's methods
MethodBuilder method1 = classA.defineMethod("method1", MethodAttributes.Public);
method1.SetParameters(classB);
// ... build method body

// define class B's methods
MethodBuilder method2 = classB.defineMethod("method2", MethodAttributes.Public);
method1.SetParameters(classA);
// ... build method body

// finish classes
classA.CreateType();
classB.CreateType();
// this time you can use GetMethod but you can not modify classes any more. 

TypeBuilder回答您的问题,在您致电之前无法获取方法、属性等的列表CreateType。但是你应该记住这些方法,属性是由你的代码创建的,所以你应该知道它们。如果你想创建一些类TypeBuilderWrapper,这是你的选择。但在我看来,你应该这样做:

  • 为您的 X 语言编写您自己的模型(XClass、、、XMethod等)。XParam
  • 将您XParser的 X 文件解析为语言模型对象。
  • 对创建的模型进行一些分析以创建模型之间的链接。例如:在sample.x上面,在B.method2,参数A a应该有一个链接到class A模型。
  • 用于Reflection.Emit创建目标程序集。记住顺序是:定义类,定义类的方法,定义类方法的主体等。然后调用CreateType完成然后全部。可以更改的顺序取决于您的语言设计。

这些都是我的想法,代码可能不起作用。当我创建我的简单愚蠢的语言时,我创建了类似的东西。希望我能帮助你。

于 2013-03-10T07:36:17.220 回答