什么是特性?
MSDN中定義為:公共語言運行時運行添加類似關鍵字的描述聲明,叫做Attribute,它對程序中的元素進行標注,如類型、方法、字段和屬性等。attribute和Microsoft.Net Framework文件的元數據保存在一起,可以用來在運行時描述你的代碼,或者在程序運行時影響應用程序的行為。
我們簡單地總結:定制特性attribute,本質上是一個類,其為目標元素提供關聯附加信息,並在運行時以反射的方式來獲取附件信息。
什么是屬性?
屬性是面向對象編程的基本概念,提供了對私有字段的封裝,C#中以get和set訪問器方法實現對可讀可寫屬性的操作,提供了安全和靈活的數據訪問封裝。
特性和屬性的區別?
在功能和應用上,二者其實沒什么太多模糊的概念交叉,因此也沒有必要放在一起比較。
attribute通用規則
1.特性可以應用的目標元素包括:程序集(assemby)、模塊(module)、類型(Type)、屬性(Property)、事件(Event)、字段(Field)、方法(Method)、參數(param)、返回值(return).
2.特性以[,]形式展示。放在緊挨着元素上
3.attribute實例,是在編譯期進行初始化,而不是運行期。
.......
示例如下:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace _01AttributeTest { class Program { static void Main(string[] args) { Tester t = new Tester(); t.CannotRun(); Type tp=typeof(Tester); MethodInfo mInfo = tp.GetMethod("CannotRun"); TestAttribute myAtt = (TestAttribute)Attribute.GetCustomAttribute(mInfo, typeof(TestAttribute)); //myAtt.RunTest(); Console.Read(); } } public class Tester { [Test("Error here.")] public void CannotRun() { } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)] public class TestAttribute : System.Attribute { public TestAttribute(string message) { Console.WriteLine(message); } public void RunTest() { Console.WriteLine("TestAttribute here. "); } } }
參考:
https://msdn.microsoft.com/zh-cn/library/system.attribute(v=vs.110).aspx
《你必須知道的.Net》