C# Attribute學習

來源:互聯網
上載者:User

標籤:

  由於項目中需要使用到序列化相關的技術,從而想到是否可以使用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本身不具有實際作用,主要是用來描述元素。但在實際使用中可以通過反射來擷取元素描述,通過對描述的分析,來進行相關的處理

C# Attribute學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.