C# 如何反映应用于返回值的属性?
考虑以下几点:C# 如何反映应用于返回值的属性?,c#,reflection,attributes,postsharp,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) { ret
[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:]语法背后的目的是什么?MethodInfo有一个ReturnTypeCustomAttributes属性,如果在此属性上调用GetCustomAttributes(),则会得到返回值atrtibutes
MethodInfo mi = typeof(Class1).GetMethod("TestMethod");
object[] attrs = mi.ReturnTypeCustomAttributes.GetCustomAttributes(true);
嘎。你的回答让我意识到PostSharp正在使用MethodBase,这就是为什么它不可用的原因。顺便说一句,如果您正在将程序集加载到只读上下文中(尽管上面的简化测试用例没有这样做,但我还是这样做了),那么这个解决方案实际上不会工作。相反,您必须使用:CustomAttributeData.GetCustomAttribute(methodInfo.ReturnParameter)还有
mi.ReturnParameter.GetCustomAttributes
等@Amy,它们在MethodBase
上不可用的原因似乎是构造函数不允许返回类型,而“非构造函数方法”允许返回类型(它们是C#方法、属性/索引器/事件的C#访问器、C#运算符)。返回void
的方法也可以在其返回值上具有自定义属性!