您如何反映应用于返回值的属性?

Amy*_*Amy 7 c# reflection attributes postsharp

考虑以下:

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
public class NotNullAttribute : Attribute
{
}

public class Class1
{
    [return: NotNull]
    public static string TestMethod([NotNull] string arg)
    {
        return arg + " + " + arg;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用System.Reflection,您是否会看到NotNullAttribute属性已应用于方法的返回值?如果你不能,[return:]语法背后的目的是什么?

Chr*_*lor 9

MethodInfo的有ReturnTypeCustomAttributes属性,如果你调用GetCustomAttributes()这个你得到的返回值atrtibutes.

MethodInfo mi = typeof(Class1).GetMethod("TestMethod");
object[] attrs = mi.ReturnTypeCustomAttributes.GetCustomAttributes(true);
Run Code Online (Sandbox Code Playgroud)

  • 还有`mi.ReturnParameter.GetCustomAttributes`等等@Amy,它们在`MethodBase`上不可用的原因似乎是构造函数不允许返回类型,而"非构造函数方法"(它们是C#方法) ,C#访问器用于属性/索引器/事件,C#操作符).返回`void`的方法也可以在返回值上有自定义属性! (3认同)
  • 顺便说一句,如果你正在将程序集加载到READ-ONLY语境中(尽管我上面的简化测试用例没有这样做),这个解决方案实际上是行不通的.相反,您必须使用:CustomAttributeData.GetCustomAttribute(methodInfo.ReturnParameter) (2认同)