C#高级编程之“代码属性”

来源:互联网 发布:es java api 工具类 编辑:程序博客网 时间:2024/05/12 06:06

  主要通过一个示例来解释这个概念。

  这个示例主要用来当方法中出现异常后,能显示编写该 方法的作者信息,以便修改。

  代码如下:

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection ;

 

namespace AttributeTest

{      

    /// <summary>

    /// 代码属性类

    /// </summary>

    [AttributeUsage (AttributeTargets .Method | AttributeTargets .Class )]

    public class CodeAttirbute:System .Attribute

    {

        private string name = string.Empty;

        private string email = string.Empty;

 

        public CodeAttirbute(string initName,string initEmail)

        {

            name = initName;

            email = initEmail;

        }

 

        public string Name

        {

            get

            {

                return name;

            }

            set

            {

                name = value;

            }

        }

 

        public string Email

        {

            get

            {

                return email;

            }

            set

            {

                email = value;

            }

        }

    }

 

    /// <summary>

    /// 工具类,通过自定义的代码属性查找某个方法的作者和Email

    /// </summary>

    public class AttributeTool

    {

        public AttributeTool()

        {

       

        }

 

        public static CodeAttirbute getAttirbute(MethodBase method)

        {

            /*

             * 返回由System.Type标识的自定义属性的数组

             * 很难理解,大概意思就是把该方法的代码属性类型化成CodeAttirbute的代码属性

            */

            object [] attributes = method.GetCustomAttributes(typeof(CodeAttirbute), true);

            return (CodeAttirbute )attributes[0];

        }

    }

 

    /// <summary>

    /// 使用上面的工具类,在出现异常后,显示该方法的作者信息

    /// </summary>

    public class UseAttributeTool

    {

        public UseAttributeTool()

        {

       

        }

 

        [CodeAttirbute("1", "2")]

        public void test()

        {

            try

            {

                int a = 1;

                int b = 0;

                int c = a / b;

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

 

                //MethodBase.GetCurrentMethod():返回表示当前正在执行的方法的MethodBase对象

                CodeAttirbute ca = AttributeTool.getAttirbute(MethodBase.GetCurrentMethod());

 

                //显示代码属性

                Console.WriteLine("Name:{0},Email:{1}",ca.Name ,ca.Email );

            }

 

        }

 

        static void Main()

        {

            UseAttributeTool u = new UseAttributeTool();

            u.test();

            Console.Read();

        }

 

    }

 

}

 

 

原创粉丝点击