Unity中的特性应用

一.特性的定义:
特性是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息
从本质上来说:自定义特性只是为某个目标元素提供了和一些额外的附加信息的关联,
编译器会在托管模块的元数据中嵌入这些额外的信息。

下面单纯的从C#方面 自定义一个特性并且简单应用一下:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1.Attrbute
{
    /// <summary>
    /// 自定义特性
    /// 1.它必须是一个类
    /// 2.它必须继承Attribute【间接】
    /// 3.它必须有符合业务需求的功能【就是内部的一个方法】
    /// </summary>
    public class AttributeDefineDemo : Attribute
    {
        public int Age;

        public AttributeDefineDemo(int age)
        {
            this.Age = age;
        }
        public bool IsAge()
        {
            return this.Age >= 18 ? true : false;
        }
    }
}
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1.Attrbute
{
    [AttributeDefineDemo(15)]
    public class AttributeDefineExamble
    {
        public void Show()
        {
            Console.WriteLine("年龄合法,执行通过");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace ConsoleApp1.Attrbute
{
    public class AttributeDefineMain
    {
        public static void main()
        {
            AttributeDefineExamble model = new AttributeDefineExamble();
			// 此处用反射绑定执行后,attribute。IsAge才会被执行。否则断点调试根本不会断住
            Type type = model.GetType();
            if (type.IsDefined(typeof(AttributeDefineDemo),true))
            {
                var attribute = type.GetCustomAttribute<AttributeDefineDemo>();
                if (attribute.IsAge())
                {
                    model.Show();
                }
            }


            model.Show();
        }
    }
}

特性用来充当过滤器。

在unity中的常用特性:
[DllImport]应用的方法 位于非托管代码中。在Unity中引用外部dll的目的是 方便集成一些外部插件,以便调用现有的动态链接库

[Serizlizable]
[MenuItem(“MyMenu/DoSomething”)]
[DontDestroyOnLoad]
[CustomeEditor]
[Conditional]…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值