7

考虑以下:

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

public class Class1
{
    [return: NotNull]
    public static string TestMethod([NotNull] string arg)
    {
        return arg + " + " + arg;
    }
}

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

4

1 回答 1

9

MethodInfo 有一个 ReturnTypeCustomAttributes 属性,如果您在此调用 GetCustomAttributes(),您将获得返回值属性。

MethodInfo mi = typeof(Class1).GetMethod("TestMethod");
object[] attrs = mi.ReturnTypeCustomAttributes.GetCustomAttributes(true);
于 2010-04-15T19:32:43.450 回答