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;
    }
}
相关推荐
Sarvartha6 小时前
final 关键字
java·开发语言
程序员Sunday6 小时前
JavaScript 事件循环面试题,宏任务与微任务怎么执行|Sunday面试指南
开发语言·javascript·面试·校招·事件循环·程序员sunday
zhangzeyuaaa7 小时前
Ruby 多线程、GVL(GIL)与 Mutex 完全指南
开发语言·前端·ruby
谢亮_vipxieliang8 小时前
用 PHP 构建轻量级 REST API:从路由到鉴权的完整实践
开发语言·后端·php
思无邪669 小时前
用 AI 做 JS 逆向:从抓包到复现的完整方法论
开发语言·javascript·人工智能
H.莓飛9 小时前
【数据结构】二叉树_OJ题
linux·开发语言·数据结构·算法
零基础12310 小时前
Ubuntu 常用命令汇总
linux·运维·开发语言
外收内放10 小时前
Python基础语法练习题(57-58)
开发语言·python
时间的拾荒人10 小时前
Qt 界面美化实战:QSS 样式表
开发语言·qt·面试
杨运交11 小时前
[076][核心模块]构建优雅的Java异常处理框架:从错误码到全局异常处理
java·开发语言