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;
    }
}
相关推荐
ECT-OS-JiuHuaShan6 分钟前
朱梁万有递归元定理,解构西方文明中心论幻觉
开发语言·人工智能·php
Aubrey-J7 分钟前
练习开发Skill——网页内容抓取Skill(website-content-fetch)
开发语言·人工智能
handler0117 分钟前
基础算法:分治
c语言·开发语言·c++·笔记·学习·算法·深度优先
2501_9249526928 分钟前
设计模式在C++中的实现
开发语言·c++·算法
大傻^30 分钟前
LangChain4j 1.4.0 快速入门:JDK 11+ 基线迁移与首个 AI Service 构建
java·开发语言·人工智能
程序猿_极客41 分钟前
【2025 最新】 MySQL 数据库安装教程(超详细图文版):从下载到配置一步到位
开发语言·数据库·mysql·mysql数据库安装
2501_945425151 小时前
C++编译期字符串处理
开发语言·c++·算法
我命由我123451 小时前
JS 开发问题:url.includes is not a function
开发语言·前端·javascript·html·ecmascript·html5·js
m0_733612211 小时前
模板编译期哈希计算
开发语言·c++·算法
阿蒙Amon1 小时前
C#常用类库-详解SqlSugar
开发语言·数据库·c#