Unity 反射Attribute基础

1.:学习笔记:
定义 :Attribute 类将预定义的系统信息或用户定义的自定义信息与目标元素相关联。目标元素可以是程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、可移植可执行文件模块、参数、属性 (Property)、返回值、结构或其他属性 (Attribute)。
msdn 例子
2.Type 为 System.Reflection 功能的根,也是访问元数据的主要方式。使用 Type 的成员获取关于类型声明的信息,如构造函数、方法、字段、属性 (Property) 和类的事件,以及在其中部署该类的模块和程序集。
表示某个类型是唯一的 Type 对象;即,两个 Type 对象引用当且仅当它们表示相同的类型时,才引用相同的对象。这允许使用参考等式来比较 Type 对象。
如果没有 ReflectionPermission,代码只能访问已加载程序集的公共成员。这包括但不限于对 Object.GetType 的不受限制的访问、通过 Type.GetType 对公共导出类型的访问以及对 GetTypeFromHandle 的访问。Type 的某些属性 (Property)(例如 FullName 和 Attributes)可以在没有 ReflectionPermission 的情况下访问。
Type 是允许多个实现的抽象基类。系统将总是提供派生类 RuntimeType。在反射中,所有以 Runtime 一词开头的类对系统中的每个对象都只能创建一次,并且这些类支持比较操作。

using System;
using System.Reflection;

namespace CustomAttrCS {
    // An enumeration of animals. Start at 1 (0 = uninitialized).
    public enum Animal {
        // Pets.
        Dog = 1,
        Cat,
        Bird,
    }

    // A custom attribute to allow a target to have a pet.
    public class AnimalTypeAttribute : Attribute {
        // The constructor is called when the attribute is set.
        public AnimalTypeAttribute(Animal pet) {
            thePet = pet;
        }

        // Keep a variable internally ...
        protected Animal thePet;

        // .. and show a copy to the outside world.
        public Animal Pet {
            get { return thePet; }
            set { thePet = Pet; }
        }
    }

    // A test class where each method has its own pet.
    class AnimalTypeTestClass {
        [AnimalType(Animal.Dog)]
        public void DogMethod() {}

        [AnimalType(Animal.Cat)]
        public void CatMethod() {}

        [AnimalType(Animal.Bird)]
        public void BirdMethod() {}
    }

    class DemoClass {
        static void Main(string[] args) {
            AnimalTypeTestClass testClass = new AnimalTypeTestClass();
            Type type = testClass.GetType();
            // Iterate through all the methods of the class.
            foreach(MethodInfo mInfo in type.GetMethods()) {
                // Iterate through all the Attributes for each method.
                foreach (Attribute attr in 
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the AnimalType attribute.
                    if (attr.GetType() == typeof(AnimalTypeAttribute))
                        Console.WriteLine(
                            "Method {0} has a pet {1} attribute.", 
                            mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
                }

            }
        }
    }
}

/*
* Output:
* Method DogMethod has a pet Dog attribute.
* Method CatMethod has a pet Cat attribute.
* Method BirdMethod has a pet Bird attribute.
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值