標籤:
由於項目中需要使用到序列化相關的技術,從而想到是否可以使用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學習