使用Reflection.Emit生成相互引用的类型

时间:2014-07-01 15:21:10

标签: c# .net reflection reflection.emit

我想在运行时通过反射生成类型,相互引用。

使用静态代码我会这样做

public class Order
{
    public int Id { get; set; }
    public Customer Customer { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public Order Order { get; set; }
}

我可以使用值类型属性成功生成我的Order和OrderDetails Type。

代码看起来像这样

var aName = new System.Reflection.AssemblyName("DynamicAssembly");
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
    aName, System.Reflection.Emit.AssemblyBuilderAccess.Run);
var mb = ab.DefineDynamicModule(aName.Name);

var tb = mb.DefineType("Order",
    System.Reflection.TypeAttributes.Public, typeof(Object));

var pbId = tb.DefineProperty("Id", PropertyAttributes.None, typeof(int), null);

现在我被困在这一行:

var pbCustomer = tb.DefineProperty("Customer", PropertyAttributes.None, ???, null);

我需要将属性的类型传递给DefineProperty方法,但此时类型不存在。 现在我可以在此时为客户创建一个类型构建器,并使用tb.CreateType()来获取类型,但这无济于事,因为客户也需要引用Order。

1 个答案:

答案 0 :(得分:7)

您的上一段大致正确,但TypeBuilder来自Type,因此您无需致电CreateType。也就是说,为每个递归类型创建类型构建器,然后定义将各个构建器本身作为返回类型传递的属性。