System.Reflection.Emit - How to add attribute to return type definition?

随声附和 提交于 2019-12-24 15:42:53

问题


I'm defining some types via System.Reflection.Emit. Imagine that I want to have method signature with some custom attributes, something like this:

[return: MyAttr]
MyType MethodName([MyOtherAttr] MyOtherType);

I use such code to generate it:

TypeBuilder t = assembly.DefineType(...);

MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot;
MethodBuilder method = t.DefineMethod("MethodName", methodAttr, typeof(MyType), new Type[] { typeof(MyOtherType) });
method.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

// return type
ParameterBuilder pbr = method.DefineParameter(0, ParameterAttributes.Retval, null);
CustomAttributeBuilder cabr = GetMyAttrBuilder();
pbr.SetCustomAttribute(cabr);

// parameter
ParameterBuilder pbp = method.DefineParameter(1, ParameterAttributes.None, null);
CustomAttributeBuilder cabp = GetMyOtherAttrBuilder();
pbp.SetCustomAttribute(cabp);

t.CreateType();

But the generated method signature is:

MyType MethodName([MyOtherAttr] MyOtherType);

The return attribute is missing :( Any idea how to achieve right behavior?

Thanks in advance


回答1:


This code in question is working well just the C# disassembler does not shows it, il one does.



来源:https://stackoverflow.com/questions/5882948/system-reflection-emit-how-to-add-attribute-to-return-type-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!