1.1特性的价值,就是作为类的元数据使用,不是对象的元数据,因为只有类有特性。而对象没有。或者说对象没有特性的那个概念,因为一个类无论创建多少对象,他的特性是固定的。
1.2 元数据的价值,就是可以通过对这个特性数据的赋值,改变类的运行行为。
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace csharp特性 { class Program { static void Main(string[] args) { Console.WriteLine("csharp特性"); Program program = new Program(); program.main(); Console.ReadKey(); } private void main() { test1(); test2(); test3(); } private void test1() { Console.WriteLine("最简单的实验"); A a = new A(); Type type = a.GetType(); FieldInfo f = type.GetField("mA1"); TestAtrribute testAtrribute = f.GetCustomAttribute<TestAtrribute>(); Console.WriteLine(testAtrribute.str); } private void test2() { Console.WriteLine("构造函数实验"); B b = new B(); Type type = b.GetType(); FieldInfo f = type.GetField("mA1"); Test2 testAtrribute = f.GetCustomAttribute<Test2>(); Console.WriteLine(testAtrribute.value); } private void test3() { Console.WriteLine("赋值实验"); C c = new C(); Type type =c.GetType(); FieldInfo f = type.GetField("mA1"); Test3 testAtrribute = f.GetCustomAttribute<Test3>(); Console.WriteLine(testAtrribute.Value); } } /// <summary> /// 最简单的实验 /// </summary> class A { [TestAtrribute] public int mA1 = 5; } public class TestAtrribute : System.Attribute { public string str = "my is TestAtrribute"; } /// <summary> /// 构造函数实验 /// </summary> class B { [Test2(1)] public int mA1 = 5; } public class Test2 : Attribute { public int value; public Test2(int a) { value = a; } } /// <summary> /// 赋值实验 /// </summary> class C { [Test3(Value=9)] public int mA1 = 5; } public class Test3: Attribute { public int Value { set; get; } } }