を使用して動的アセンブリを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
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加