zoukankan      html  css  js  c++  java
  • C#提高--------------获取方法返回值的自定义特性(Attribute)

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

    转载 2013年05月08日 10:54:42

    来自: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";

            }

        }

    }

  • 相关阅读:
    js数组求交集
    php安装oci8和pdo_oci扩展实现连接oracle数据库
    nginx配置静态资源压缩
    SHELL递归遍历文件夹下所有文件
    PHP函数获取临时文件目录
    php去除文件bom头
    tcpdump抓取udp报文
    linux获取当前运行级别
    当安装软件后提示依赖没有安装时
    Ubuntu卸载通过apt-get命令安装的软件
  • 原文地址:https://www.cnblogs.com/w-wfy/p/7670969.html
Copyright © 2011-2022 走看看