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;
    }
}
相关推荐
BUG研究员_5 小时前
Runnable与LCEL
开发语言·人工智能·python
牛艺翔6 小时前
C++基础
开发语言·c++
键盘会跳舞7 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
美味蛋炒饭.7 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
yanaiding7 小时前
C# WPF 独立开发看图工具 PixSight 经验介绍(二)—— 水印模块开发实录
图像处理·c#·wpf·个人开发
我星期八休息7 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
问商十三载7 小时前
RAG 检索效果差怎么排查?2026 五层诊断法完整指南
开发语言·人工智能·windows·python·算法
不负岁月无痕7 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
SomeB1oody8 小时前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程
淡海水8 小时前
15-02-YooAsset面试篇-Unity架构设计与源码
java·unity·面试·c#·游戏引擎·yooasset