gpt4 book ai didi

c# - 反射发射生成简单的继承

转载 作者:行者123 更新时间:2023-11-30 15:53:13 24 4
gpt4 key购买 nike

我正在尝试通过 reflection.emit 动态生成以下类层次结构:

public class Main
{
public class A { A(){} }
public class B : A { B() : base() {} }
}

这是我试图在 .net core 框架上运行的程序(在 .net 上使用了类似的程序,但异常是相同的):

using System;
using System.Reflection;
using System.Reflection.Emit;
public class Program
{
public static void Main()
{
AssemblyBuilder assemBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName() { Name = "DynamicAssembly" }, AssemblyBuilderAccess.Run);
TypeBuilder main_builder = assemBuilder.DefineDynamicModule("DynamicModule").DefineType("Main", TypeAttributes.Public);

TypeBuilder a_builder = main_builder.DefineNestedType("A", TypeAttributes.NestedPublic);
TypeBuilder b_builder = main_builder.DefineNestedType("B", TypeAttributes.NestedPublic, a_builder);

var a_constr = a_builder.DefineDefaultConstructor(MethodAttributes.Public);
var b_cnstr = b_builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);

{
// Creation b constructor
var il_gen = b_cnstr.GetILGenerator();
il_gen.Emit(OpCodes.Ldarg_0);
il_gen.Emit(OpCodes.Call, a_constr);
il_gen.Emit(OpCodes.Ret);
}
a_builder.CreateType();
b_builder.CreateType();
main_builder.CreateType();
}
}

但是在执行过程中,程序在 b_builder.CreateType() 处失败并出现异常消息(这是我无法调试的 .net core 函数): enter image description here

reflection.emit 错误吗?我不知道我的代码有什么问题

最佳答案

文档中TypeBuilder.CreateType备注部分的第一行告诉我们:

If this type is a nested type, the CreateType method must be called on the enclosing type before it is called on the nested type

https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.typebuilder.createtype

所以改变调用顺序,它应该可以工作:

main_builder.CreateType();
a_builder.CreateType();
b_builder.CreateType();

参见 https://dotnetfiddle.net/bxYCQb

关于c# - 反射发射生成简单的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52740161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com