C# 特性(attribute)
Atrribute表示自定义特性的基类。
其派生类约定惯例以Attribute结尾命名,如:AttributeUsageAttribute、TestAttribute。
下面获取如何定制特性attribute和获取自定义特性信息:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace AttributeDemo { [Test("it's a class1")] [Test("it's a class2")] [Test("it's a class3")] class Program { [Test("it's a property")] public String Name { get; set; } static void Main(string[] args) { Program p = new Program(); Type type = typeof(Program); MethodInfo method = type.GetMethod("AttributeTest"); MemberInfo member = type.GetMember("Name").First(); //利于反射分别获取类、方法、属性的算定义特性实例化 TestAttribute[] myAttr = (TestAttribute[])Attribute.GetCustomAttributes(type, typeof(TestAttribute)); TestAttribute myAttr2 = (TestAttribute)Attribute.GetCustomAttribute(method, typeof(TestAttribute)); TestAttribute myAttr3 = (TestAttribute)Attribute.GetCustomAttribute(member, typeof(TestAttribute)); foreach (TestAttribute attr in myAttr) { Console.WriteLine(attr.Message);//输出类Program的自定义特性 } Console.WriteLine(myAttr2.Message); //输出方法AttributeTest的自定义特性 Console.WriteLine(myAttr3.Message); //输出属性Name的自定义特性 //调用方法AttributeTest object obj = Activator.CreateInstance(typeof(Program)); method.Invoke(obj, null); } [Test("it's a method")] public void AttributeTest() { Console.WriteLine("我还可以这样被调用"); } } [AttributeUsageAttribute(AttributeTargets.All,AllowMultiple=true,Inherited=true)] public class TestAttribute : Attribute { public String Message { get; set; } public TestAttribute(string message) { this.Message = message; } } }