2015-04-22 21 views
2

我觉得我的问题的标题是有点混乱,所以让我澄清一下。为了我的目的,我将MarshalAsAttribute应用于参数和返回类型。使用ParameterBuilder将自定义属性添加到返回值;属性在反映时不显示 - 为什么?

(注:最初我没想到这是工作在所有,但在这里,这个问题导致我发布了这个问题:System.Reflection.Emit - How to add attribute to return type definition?

所以我们可以说,我对动态的方法创建委托类型与此签名:

[return: MarshalAs(UnmanagedType.I1)] 
internal static extern Boolean SomeFunction([MarshalAs(UnmanagedType.LPStr)] string argument); 

类似下面的代码,我能做到这一点罚款既为函数参数和返回类型(注意我在这里省略一堆为了简洁):

var currentParameterAttributeBuilder = methodBuilder.DefineParameter(parameterPosition, currentParameterAttributes, 
        parameterName); 
var attributeParams = new Type[] { typeof(UnmanagedType) }; 
var attributeConstructorInfo = typeof(MarshalAsAttribute).GetConstructor(attributeParams); 
var customParameterAttribute = new CustomAttributeBuilder(attributeConstructorInfo, new object[] { currentArgument.MarshallingType }); 
currentParameterAttributeBuilder.SetCustomAttribute(customParameterAttribute); 

然而,当我去通过反射来检查属性的存在,如在以下几点:

// This works and retrieves the MarshalAs attribute, 'param' being a parameter retrieved from a foreach iteration over type.GetMethod("Invoke").GetParameters() 
var argumentCustomAttributes = param.GetCustomAttributes(typeof(MarshalAsAttribute), false); 
// This doesn't work; it doesn't 'see' the MarshalAs attribute 
var returnCustomAttributes = type.GetMethod("Invoke").ReturnType.GetCustomAttributes(typeof(MarshalAsAttribute), false); 

所以基本上,返回类型的属性不能被通过反射观看,但它是在实际应用,如在这个.NET反射器截图(此签名不同于上面,但演示了我的观点):

example image < - 我没有足够的信誉来嵌入图像,抱歉。

我只是好奇,如果任何人都知道这是为什么,因为我花了相当多的时间与它挣扎前我碰到其他职位迷迷糊糊地意识到这实际上是正确应用。希望我已经正确格式化了这个;这是我第一次发布。

回答

0

看来,因为我用错了MethodInfo的财产,我应该更加重视。

而不是MethodInfo的“ReturnType”,我应该使用“ReturnParameter”,或者对于这个特定的情况,“ReturnTypeCustomAttributes” - 或者为此目的工作。 “ReturnParameter”特别提到了自定义修饰符。哎呀!

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