.NET(C#):获取方法返回值的自定义特性(Attribute)

来自:http://www.cnblogs.com/mgen/archive/2011/11/02/2233374.html

.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. 两种方法都可以获取返回值的自定义特性。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值