C# 使用ParameterBuilder向返回值添加自定义属性;属性不为';反射时不显示——为什么?

C# 使用ParameterBuilder向返回值添加自定义属性;属性不为';反射时不显示——为什么?,c#,reflection,marshalling,C#,Reflection,Marshalling,我认为我的问题标题有点混乱,所以让我澄清一下。出于我的目的,我将MarshalAsAttribute应用于参数和返回类型 (注意:起初我认为这根本不起作用,但这里的这个问题让我提出了这个问题:) 假设我正在为具有此签名的方法动态创建委托类型: [返回:Marshallas(UnmanagedType.I1)] 内部静态外部布尔SomeFunction([Marshallas(UnmanagedType.LPStr)]字符串参数); 使用类似于下面的代码,我可以很好地处理函数参数和返回类型(注意

我认为我的问题标题有点混乱,所以让我澄清一下。出于我的目的,我将MarshalAsAttribute应用于参数和返回类型

(注意:起初我认为这根本不起作用,但这里的这个问题让我提出了这个问题:)

假设我正在为具有此签名的方法动态创建委托类型:

[返回:Marshallas(UnmanagedType.I1)]
内部静态外部布尔SomeFunction([Marshallas(UnmanagedType.LPStr)]字符串参数);
使用类似于下面的代码,我可以很好地处理函数参数和返回类型(注意,为了简洁起见,这里省略了一堆):

var currentParameterAttributeBuilder=methodBuilder.DefineParameter(parameterPosition,currentParameterAttributes,
参数名);
var attributeParams=新类型[]{typeof(UnmanagedType)};
var attributeConstructorInfo=typeof(MarshalAsAttribute).GetConstructor(attributeParams);
var customParameterAttribute=新的CustomAttributeBuilder(attributeConstructorInfo,新对象[]{currentArgument.MarshallingType});
currentParameterAttributeBuilder.SetCustomAttribute(customParameterAttribute);
但是,当我通过反射检查属性是否存在时,例如:

//这可以工作并检索MarshalAs属性,'param'是通过type.GetMethod(“Invoke”).GetParameters()上的foreach迭代检索到的参数
var argumentCustomAttributes=param.GetCustomAttributes(typeof(MarshalAsAttribute),false);
//这不管用;它没有“看到”MarshalAs属性
var returnCustomAttributes=type.GetMethod(“调用”).ReturnType.GetCustomAttributes(typeof(MarshalAsAttribute),false);
因此,基本上,返回类型的属性不能通过反射查看,但它实际上是应用的,如.NET Reflector屏幕截图所示(此签名与上面不同,但说明了我的观点):


似乎我应该更加注意,因为我使用了错误的MethodInfo属性

我不应该使用MethodInfo的“ReturnType”,而应该使用“ReturnParameter”,或者对于这个特定的案例,“ReturnTypeCustomAttributes”——两者都可以用于此目的。“ReturnParameter”特别提到自定义修饰符。哎呀

var returnCustomAttributes=type.GetMethod(“Invoke”).ReturnParameter.GetCustomAttributes(typeof(MarshalAsAttribute),false);