使用ParameterBuilder将自定义属性添加到返回值;属性在反映时不显示 - 为什么?

时间:2015-04-22 23:36:20

标签: c# reflection marshalling

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

(注意:最初我认为这根本不起作用,但这个问题让我发布这个问题: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 Reflector屏幕截图所示(此签名与上面不同但是证明了我的观点):

example image< - 我没有足够的声誉嵌入图片,抱歉。

我只是好奇,如果有人知道为什么会这样,因为我花了很多时间挣扎着它,然后我偶然发现了其他帖子,并意识到它实际上是正确应用的。希望我已经正确地格式化了这个;这是我第一次发帖。

1 个答案:

答案 0 :(得分:0)

当我使用错误的MethodInfo属性时,我似乎应该多加注意。

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

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
相关问题