c#-特性理解

所谓特性就是系统级别的属性。

一直对特性和属性的理解比较模糊,发现了下面这句话

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));
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值