所谓特性就是系统级别的属性。
一直对特性和属性的理解比较模糊,发现了下面这句话
PropertyInfo Class
发现属性 (Property) 的属性 (Attribute) 并提供对属性 (Property) 元数据的访问。
属性是一个类别,而给这个类别定义的属性就是特性,任何一个属性的类型也是用一个对象表示的,
而表示这个类型的属性,就叫特性。我们可以给属性添加特性,就是给这个属性添加的类型添加一个特性。
就是给这个属性表示的对象,添加一个属性,这个属性对应的数据就是元数据,系统级别的数据。
代码
using System;
using System.Reflection;
/*
* 属性的属性叫特性(系统级别的属性,作为元数据的属性)
* 引用:发现属性 (Property) 的属性 (Attribute) 并提供对属性 (Property) 元数据的访问。
*/
namespace 反射
{
[AttributeUsage(AttributeTargets.Property)]
public class MyAttributeAttribute : System.Attribute {
public MyAttributeAttribute(int m) {
mA = m;
}
public int mA;
}
class Program
{
public Program() {
A = 0;
}
[MyAttributeAttribute(5)]
public int A { set; get; }
static void Main(string[] args)
{
Console.WriteLine("特性理解");
Program p = new Program();
p.Property(p);
Console.ReadLine();
}
private void Property(Object o)
{
Type t = o.GetType();
Console.WriteLine("属性Propertie:");
foreach (PropertyInfo pi in t.GetProperties())
{
Console.WriteLine("属性名:" + pi.Name);
Console.WriteLine("属性值:" + pi.GetValue(this));
GetCustomAttributes(pi);
}
}
private void GetCustomAttributes(PropertyInfo propertyInfo) {
Console.WriteLine("Attributes:");
object[] attributes = propertyInfo.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
MyAttributeAttribute myAttributeAttribute = (MyAttributeAttribute)attributes[i];
Console.WriteLine(" 特性名:" + attributes[i].GetType().Name);
Console.WriteLine(" 特性的属性名:" + attributes[i].GetType().GetField("mA").Name);
Console.WriteLine(" 特性的属性值:" + attributes[i].GetType().GetField("mA").GetValue(myAttributeAttribute));
}
}
}
}