由于以上两篇文章对于特性的描述比较详细,在此就不写太多废话,直接上实例(模仿Json解析,并使用Attribute将一个属性的值引用到另一个属性),也行效果会更好。例子比较简单,主要起引导作用。
using System;
using System.Reflection;
 
namespace Attribute
{
    class Program
    {
        static void Main( string[] args)
        {
            string s = "{A:1,B:2}";
            AtoC ab = Deserializer< AtoC>(s);
 
            Console.WriteLine( "A=" + ab.A);
            Console.WriteLine( "B=" + ab.B);
            Console.WriteLine( "C=" + ab.C);
        }
 
        private static T Deserializer<T>( string s) where T: new ()
        {
            Type t = typeof(T);
            T ins = new T();
            //解析所有的属性
            string[] sour = s.TrimStart(‘{‘).TrimEnd(‘}‘ ).Split(‘,‘ );
            foreach ( string sou in sour)
            {
                string key = sou.Split( ‘:‘)[0];
                string value = sou.Split( ‘:‘)[1];
                //获取属性值
                PropertyInfo props = t.GetProperty(key);
                props.SetValue(ins, value, null);
 
                //获取所有的特性
                object[] att = props.GetCustomAttributes(typeof(HelpAttribute ), false );
                //将获到的特性所指向的对象赋值
                foreach ( HelpAttribute a in att)
                {
                    t.GetProperty(a.Param).SetValue(ins, value, null);
                }
            }
            return ins;
        }
    }
 
    [AttributeUsage( AttributeTargets.Property, AllowMultiple = false, Inherited = true )]
    class HelpAttribute : Attribute
    {
        public HelpAttribute( string param)
        {
            this.param = param;
        }
        //只读属性
        private string param;
        public string Param { get { return param; } }
    }
 
    public class AtoC
    {
        [ Help( "C")]
        public string A { get; set; }
        public string B { get; set; }
        public string C { get; set; }
    }
}
  
总结:Attribute本身不具有实际作用,主要是用来描述元素。但在实际使用中可以通过反射来获取元素描述,通过对描述的分析,来进行相关的处理