码迷,mamicode.com
首页 > Windows程序 > 详细

C#的Attribute

时间:2015-09-04 09:53:15      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace codeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //通过反射来获取Attribute中的信息
            MyAttribute myattribute;
            foreach (var attr in typeof(MyClass).GetCustomAttributes(true))
            {
                myattribute = attr as MyAttribute;
                Console.WriteLine(myattribute.Name);
            }

            Console.ReadLine();
        }
    }

    //自定义Attribute经常用到 AttributeUsage ,可以限制自定义Attribute的使用范围
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    class MyAttribute : Attribute
    {
        //MyAttribute必须继承Attribute
        string name;

        public MyAttribute(string nameIn)
        {
            this.name = nameIn;
        }

        public string Name
        {
            get
            {
                return this.name;
            }
        }

        public string desc
        {
            get;
            set;
        }
    }

    //MyAttribute可以缩写为  My
    [My("MyAttribute",desc="MyClass")]
    class MyClass
    {

    }

}

 

C#的Attribute

标签:

原文地址:http://www.cnblogs.com/lgxlsm/p/4781231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!