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;
    }
}
相关推荐
froginwe1115 小时前
Python 循环嵌套
开发语言
@大迁世界15 小时前
AI还替不了的JS能力
开发语言·前端·javascript·人工智能·ecmascript
ZJH__GO15 小时前
java项目-流水线线程池
java·开发语言
weixin_4280053015 小时前
.vdproj项目加载提示不兼容问题处理
c#·visual studio·.vdproj·.vdproj不兼容
放逐者-保持本心,方可放逐15 小时前
Go + WebAssembly 构建树木数据统计分析系统
开发语言·golang·wasm·javascipt
心前阳光15 小时前
Unity之PhotonServer使用注意
unity·游戏引擎
ftpeak15 小时前
深入浅出 LoongSuite Python Agent:让你的 AI 应用「透明化」(下篇)
开发语言·人工智能·ai·ai编程·ai开发
希望永不加班16 小时前
SpringBoot 消息幂等性设计:防重复消费
java·开发语言·spring boot·后端·spring
l1t16 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程7-8
开发语言·python
我是一颗柠檬16 小时前
【JDK8新特性】CompletableFuture异步编程Day10
java·开发语言·后端·intellij-idea