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;
    }
}
相关推荐
兰令水1 天前
leecodecode【回溯组合】【2026.6.5打卡-java版本】
java·开发语言
zyl837211 天前
Python 线性代数:矩阵与向量
开发语言·python·机器学习
雪豹阿伟1 天前
18.C# —— 三层结构 + 接口架构实战(UI+Model+DAL+IDAL)
c#·上位机
AC赳赳老秦1 天前
OpenClaw+MySQL 深度应用:自动生成建表语句、索引优化建议与数据迁移脚本
开发语言·数据库·人工智能·python·mysql·算法·openclaw
yangyongdehao301 天前
桌面宠物开发记:从Rust到Tauri的探索之旅
开发语言·rust·宠物
想取一个与众不同的名字好难1 天前
安卓设置亮度的时候,系统会在100%与0%反复横跳
android·java·开发语言
郝学胜-神的一滴1 天前
Qt 高级开发 025:打造优雅界面的艺术与高效重构之道
开发语言·c++·qt·程序人生·重构·软件构建·用户界面
一晌小贪欢1 天前
第19节:地理空间分析——使用 Geopandas 绘制热力地图
开发语言·python·数据分析·pandas·数据可视化
Byte Wizard1 天前
C语言文件操作
c语言·开发语言
scan7241 天前
SystemMessage,HumanMessage,AIMessage,ToolMessage
开发语言·前端·javascript