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

标签 c# reflection.emit

在使用 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/

相关文章:

c# - 检测互联网连接

c# - TextBox AutoPostBack 抢占更多事件

c# - 替换 lambda 表达式中的参数类型

c# - 适用于移动应用程序 (Android/iOS) 的 Xamarin 中的 DataGridView

c# - 创建代理实例失败,出现 COMException(IIS、Windows Server 2012、NHibernate)

c# - System.Windows.Controls.UserControl 加载事件在 'Unloaded' 时触发

c# - 为什么 DynamicMethod 在 x64 上这么慢?

c# - 尝试调用方法时出错

c# - Reflection.Emit 如何分配不兼容的类型?

c# - 如何发出静态外部方法?