C#自定义特性

特性的用处

一般用来影响某一个类的个别字段或者方法

定义特性

需要将类继承Attribute

可以通过构造函数的方式影响使用特性的方法

可以通过给自定义的特性通过加AttributeUsage特性的方法进行进一步管理

AttributeUsage特性默认传三个参数

第一个参数一般用来约束此自定义特性是否可以给类和字段使用

第二个参数若是为false,则不可以给一个类多个特性

若是为true则可以使用

第三个参数一般控制此自定义特性是否可以被继承

案例展示

在拓展类内部实现

cs 复制代码
    /// <summary>
    /// 获取特性
    /// </summary>
    public static T GetAttribute<T>(this object obj) where T : Attribute
    {
        return obj.GetType().GetCustomAttribute<T>();
    }
    /// <summary>
    /// 获取特性
    /// </summary>
    /// <param name="type">特性所在的类型</param>
    /// <returns></returns>
    public static T GetAttribute<T>(this object obj, Type type) where T : Attribute
    {
        return type.GetCustomAttribute<T>();
    }

测试案例

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;

[Text(false)]
public class Test : MonoBehaviour
{
    private int num;
    void Start()
    {
        TextAttribute text = this.GetAttribute<TextAttribute>();

        if (text.canSwitch)
        {
            Debug.Log("可以切换");
        }
    }

    void Update()
    {
        
    }
}

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Field,AllowMultiple = false)]
public class TextAttribute : Attribute
{
    public bool canSwitch;
    public TextAttribute(bool canSwitch)
    {
        this.canSwitch = canSwitch;
    }
}
相关推荐
一个响当当的名号16 分钟前
lectrue9 索引并发控制
java·开发语言·数据库
2401_8321319516 分钟前
模板错误消息优化
开发语言·c++·算法
进阶小白猿20 分钟前
Java技术八股学习Day30
java·开发语言·学习
lead520lyq21 分钟前
Golang本地内存缓存
开发语言·缓存·golang
zhaotiannuo_199822 分钟前
Python之2.7.9-3.9.1-3.14.2共存
开发语言·python
2601_9498683632 分钟前
Flutter for OpenHarmony 电子合同签署App实战 - 主入口实现
开发语言·javascript·flutter
helloworldandy1 小时前
高性能图像处理库
开发语言·c++·算法
2401_836563181 小时前
C++中的枚举类高级用法
开发语言·c++·算法
chao1898441 小时前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法
EmbedLinX1 小时前
C++ 面向对象
开发语言·c++