自定义Attribute(原创)

    一.理论

                 Attribute在msdn中被翻译成属性,我感觉不太适合.我更赞成前辈王涛(<你必须知道的.net>的作者)对之的称呼--特性.

          看过王涛前辈的书,记得王涛前辈对特性做过这样的描述:   特性attribute,本质上是一个类,其为目标元素提供关联附加信息,

         并在运行期以反射的方式来获取附加信息.感觉不太全面.但目前还没有太多时间找相关的资料,所以姑且先这样认为.

   二.示例

            0.示例方案图

                

            1.自定义Attribute(DefaultAttribute.cs)

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

namespace TestAttribute
{
    public class DefaultAttribute:Attribute
    {
        public string DefaultName { get; set; }
    }
}

 

           2.使用自定义的Attribute (Model.cs)        

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

namespace TestAttribute
{
    public  class Model
    {
        [Default(DefaultName="姓名")]
        public String name { get; set; }
   
        [Default(DefaultName="成绩")]
        public Byte Score { get; set; }
    }
}

          3.测试按钮代码(如下)          

            String modelpropertiesattributes ="";
            Type t = typeof(Model);
            PropertyInfo[] pis = t.GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                modelpropertiesattributes+=((DefaultAttribute)pi.GetCustomAttributes(true)[0]).DefaultName+":";
            }
            modelpropertiesattributes=modelpropertiesattributes.Substring(0, modelpropertiesattributes.Length-1);
            MessageBox.Show(modelpropertiesattributes);

   4.测试结果(如下图)

        

                

posted @ 2011-10-23 19:13  --中庸--  阅读(327)  评论(0编辑  收藏  举报