gpt4 book ai didi

c# - 自定义属性未正确添加到 Reflection.Emit 程序集中

转载 作者:行者123 更新时间:2023-11-30 23:03:57 26 4
gpt4 key购买 nike

在使用 Relection.Emit 创建动态程序集时,我试图创建一个方法并使用 System.Runtime.CompilerServices.MethodImplAttribute 对其进行修饰。我使用该方法成功创建并保存了程序集,但是当我加载保存的程序集时,我的方法似乎没有任何自定义属性。这是我创建程序集的代码:

ConstructorInfo methodImplCtor = typeof(System.Runtime.CompilerServices.MethodImplAttribute).GetConstructor(new[] { typeof(System.Runtime.CompilerServices.MethodImplOptions) });
// stores the constructor I wish to use

AssemblyBuilder assm = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("MyAssembly"), AssemblyBuilderAccess.Save);
ModuleBuilder module = assm.DefineDynamicModule("MyAssembly", "MyAssembly.dll", false);
TypeBuilder type = module.DefineType("MyAssembly.MyType", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed);
MethodBuilder method = type.DefineMethod("MyMethod", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig, typeof(int), new[] { typeof(int) });

method.SetCustomAttribute(new CustomAttributeBuilder(methodImplCtor, new object[] { System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining }));

ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);

type.CreateType();
assm.Save("MyAssembly.dll");

上面的代码运行后,我获取 MyAssembly.dll 文件并在不同的项目中引用它。当我运行这段代码时,它报告我的方法中有零个自定义属性:

var attributes = typeof(MyAssembly.MyType).GetMethod("MyMethod").GetCustomAttributes(false);
// empty array!

最佳答案

那是因为有些属性并不是真正的属性,而是实际上的 IL 原语。这适用于 [Serializable] 和其他一些 - 包括(显然)这个;这是来自“ildasm”的 IL:

.method public hidebysig static int32  MyMethod(int32 A_0) cil managed aggressiveinlining
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
} // end of method MyType::MyMethod

注意 aggressiveinlining

关于c# - 自定义属性未正确添加到 Reflection.Emit 程序集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49619097/

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