C# Attribute学习

  由于项目中需要使用到序列化相关的技术,从而想到是否可以使用C#中的特性,特此花了近两小时学习了一下。

  对于特性的学习,主要参考了两篇博文,特此感谢。以下附链接:

  http://www.cnblogs.com/luckdv/articles/1682488.html

  http://www.cnblogs.com/liuxinxin/articles/2265672.html

  在学习的过程中,一直以为特性对于元素可以起到什么实质性的影响,例如系统内置的特性,Obsolete可以阻止用户使用所引用该特性的元素。

  由于以上两篇文章对于特性的描述比较详细,在此就不写太多废话,直接上实例(模仿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本身不具有实际作用,主要是用来描述元素。但在实际使用中可以通过反射来获取元素描述,通过对描述的分析,来进行相关的处理
原文地址:https://www.cnblogs.com/kai364/p/4417436.html