2010-04-15 50 views
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:]語法背後的目的是什麼?

回答

9

MethodInfo有一個ReturnTypeCustomAttributes屬性,如果你對此調用GetCustomAttributes(),你會得到返回值atrtibutes。

MethodInfo mi = typeof(Class1).GetMethod("TestMethod"); 
object[] attrs = mi.ReturnTypeCustomAttributes.GetCustomAttributes(true); 
+0

Gah。你的回答讓我意識到PostSharp正在使用MethodBase,這就是爲什麼它不可用。謝謝。 – Amy 2010-04-15 19:39:23

+2

順便說一句,如果您正在將程序集加載到READ-ONLY上下文中(儘管我上面的簡化測試用例沒有這樣做),但此解決方案實際上不起作用。相反,你必須使用:CustomAttributeData.GetCustomAttribute(methodInfo.ReturnParameter) – 2011-12-09 04:21:24

+3

還有'mi.ReturnParameter.GetCustomAttributes'等等@Amy,它們在MethodBase上不可用的原因似乎是構造函數不允許返回類型,而「非構造函數方法」(它們是C#方法,屬性/索引器/事件的C#訪問器,C#運算符)。返回'void'的方法在返回值上也可以有自定義屬性! – 2014-01-13 14:27:03