特性 C# Unity

特性用于添加元数据(描述数据的数据)
可以放在脚本中的“类、属性或函数上方“向程序添加声明性信息,一个程序可添加多个特性;

Unity中常用的特性
  • [Header(“name”)] :在 Inspector 中的某些字段上方添加标题
  • [Range(min,max)] :使脚本中的float或int类型的变量受限于特定范围,且在Inspector面板中显示为滑动条;
  • [HideInInspector] :使变量不显示在Inspector中,但进行序列化(变为二进制字节流,使其状态信息转换为可存储或传输的形式);
  • [AddComponentMenu] :在Component菜单中放置脚本,改进添加脚本时的工作流程;
  • [RequireComponent(typeof(Component))] :向GameObject添加使用RequireComponent的脚本时,会自动将需要的组件添加到GameObject中;
.NET框架的特性
AttributeUsage预定义特性

描述如何使用一个自定义特性类,规定了特性可应用到的项目的类型;

[AttributeUsage(validon,AllowMultiple=allowmultiple,Inherited=inherited)]

第一个参数:规定特性可被放置的语⾔元素,它是枚举器 AttributeTargets 的值的组合,默认值是 AttributeTargets.All;
第二个参数:表示特性是否可多次使用,通过AllowMultiple=bool进行声明;
第三个参数:表示特性是否可以被继承,通过Inherited=bool进行声明;

注:AttributeUsage特性是单次使用的特性,它无法应用于同一个类超过一次;

自定义特性

自定义特性:用于存储声明性的信息,且可在运行时被检索;

  • 声明自定义特性:自定义特性的类应派生自System.Attribute类;
  • 构建自定义特性,每个特性必须至少有一个构造函数,用于传递参数;
  • 在目标程序元素上应用自定义特性:把特性放置在紧接着它的目标之前即对目标应用特性;
  • 通过反射访问特性:(自定义特性不被检索及操作则是没有价值的)使用GetCustomAttributes方法可检索通过自定义特性定义的信息,返回对象数组,这些对象在运行时等效于源代码中的特性;

特性只能通过反射拿到,程序可通过反射检查自己的元数据或其他程序内的元数据:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class MyConditionAttribute : Attribute{
    public string author;
    public string LastDate;
    public MyConditionAttribute(string author){
        this.author = author;
    }
}

//Attribute可省略
[MyConditionAttribute("Albert", LastDate = "2020.5.13"), MyCondition("Tom", LastDate = "2020.10.13")]
public class UsersAttributes : MonoBehaviour{}

public class UsesAttributeObserver : MonoBehaviour{
    private void PrintAttributeMsg(){
        Type type = typeof(UsersAttributes);
        object[] atts = type.GetCustomAttributes(false);
        for (int i = 0; i < atts.Length; i++){
            if (atts[i] is MyConditionAttribute){
                MyConditionAttribute authorObj = atts[i] as MyConditionAttribute;
                Debug.Log(authorObj.author);
                Debug.Log(authorObj.LastDate);
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值