attribute

Attribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    /// <summary>
    /// 实例化记录
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
    public class RecordAttribute:Attribute
    {
        string recordType;
        string author;
        DateTime date;
        string memo;
        // 对于位置参数,通常只提供get访问器   
        public string RecordType { get { return recordType; } }
        public string Author { get { return author; } }
        public DateTime Date { get { return date; } }
        public string Memo
        {
            get { return memo; }
            set { memo = value; }
        }
        public RecordAttribute(string recordType, string author, string date)
        {
            this.recordType = recordType;
            this.author = author;
            this.date = Convert.ToDateTime(date);  
        }
    }
}

 

调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //DemoClass demo = new DemoClass();
            //Console.WriteLine(demo.ToString());
            Type t=typeof(DemoClass);
            Console.WriteLine("下面列出应用于 {0} 的RecordAttribute属性:", t);
            // 获取所有的RecordAttributes特性   
            object[] records = t.GetCustomAttributes(typeof(RecordAttribute),false);
            foreach (RecordAttribute record in records)
            {
                Console.WriteLine("   {0}",record);
                Console.WriteLine("      类型:{0}", record.RecordType);
                Console.WriteLine("      作者:{0}", record.Author);
                Console.WriteLine("      日期:{0}", record.Date.ToShortDateString());
                if (!String.IsNullOrEmpty(record.Memo))
                {
                    Console.WriteLine("      备注:{0}", record.Memo);
                }   
            }
            Console.Read();
        }
    }
    [Record("update", "wjl", "2017-1-4", Memo = "这个类仅供演示")]
    [Record("update", "wjl1", "2017-1-5")]
    [Record("create", "wjl2", "2017-1-6")]
    public class DemoClass
    {

    }
}

 

 

 

posted @ 2017-01-09 09:58  wjl910  阅读(104)  评论(0)    收藏  举报