代码改变世界

C#拾遗系列(7):自定义属性

2008-06-18 14:52  敏捷的水  阅读(1530)  评论(0编辑  收藏  举报

1 .描述

属性提供功能强大的方法以将声明信息与 C# 代码(类型、方法、属性等)相关联。属性与程序实体关联后,即可在运行时使用名为“反射”的技术查询属性。

属性以两种形式出现:

  • 一种是在公共语言运行库 (CLR) 中定义的属性。

  • 另一种是可以创建的用于向代码中添加附加信息的自定义属性。此信息可在以后以编程方式检索。

2. 示例代码:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace NetTest

{

    public class TestAttribute

    {

        public void Test()

        {           

            PrintAuthorInfo(typeof(CustomAttribute));       

        }

 

        /*

        Obsolete 属性将某个程序实体标记为一个建议不再使用的实体。每次使用被标记为已过时的实体时,

        随后将生成警告或错误,这取决于属性是如何配置的,第二个参数是true时,编译时显示错误

        */

        [Obsolete("please use aonther method,this is obsolate",true)]

        public void TestObsolate()

        {

            Console.Out.WriteLine("welcome");

 

        }

 

        private static void PrintAuthorInfo(System.Type t)

        {

            System.Console.WriteLine("Author information for {0}", t);

            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

 

            foreach (System.Attribute attr in attrs)

            {

                if (attr is Author)

                {

                    Author a = (Author)attr;

                    System.Console.WriteLine("   {0}, version {1:f}", a.Name, a.version);

                }

            }

        }

 

        //应用自定义属性

        [Author("Jack",version=1.0)]

        [Author("TJ",version=2.0)]

        class CustomAttribute

        {

            public void Test()

            {

 

                Console.Out.WriteLine("Test custom attribute");

            }       

        }

 

        //自定义的属性,集成属性类

        [System.AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,AllowMultiple=true)]

        class Author : System.Attribute

        {

            private string name;

            public double version;

 

            public Author(string name)

            {

                this.name = name;

                version = 1.0;

            }

 

            public string Name

            {

 

                get { return this.name; }

            }

 

        }

    }

 

}