.NET中特性的索取就是圍繞著ICustomAttributeProvider介面(System.Reflection命名空間內),而MethodInfo類的ReturnTypeCustomAttributes屬性直接返回方法傳回值的ICustomAttributeProvider介面對象。同時MethodBase的ReturnParameter屬性返回方法傳回值資訊(ParameterInfo),而ParameterInfo也是繼承ICustomAttributeProvider的,所以這兩個屬性都可以得到方法傳回值的特性。注意基類MethodBase沒有相應屬性,由於ConstructorInfo(代表建構函式資訊)沒有傳回值。
代碼:
using System;
using System.Reflection;
namespace Mgen
{
[AttributeUsage(AttributeTargets.ReturnValue)]
class MyAttr : Attribute
{
public int Data { get; set; }
}
class Program
{
static void Main(string[] args)
{
var method = typeof(Program).GetMethod("doo");
test(method.ReturnTypeCustomAttributes);
test(method.ReturnParameter);
}
static void test(ICustomAttributeProvider customAttrProvider)
{
if (customAttrProvider.IsDefined(typeof(MyAttr), false))
{
var att = (MyAttr)customAttrProvider.GetCustomAttributes(typeof(MyAttr), false)[0];
Console.WriteLine(att.Data);
}
}
[return: MyAttr(Data = 17)]
public static string doo()
{
return "hehe";
}
}
}
輸出兩個17. 兩種方法都可以擷取傳回值的自訂特性。