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 小时前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia
喜欢的名字被抢了2 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi
从零开始的代码生活_4 小时前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
wabs6664 小时前
关于单调栈【力扣739.每日温度的思考】
java·开发语言
AOwhisky4 小时前
Python 学习笔记(第三期)——流程控制核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发·流程控制
逆向编程5 小时前
Socket异常连接自动清理方案
开发语言
va学弟6 小时前
Java 网络通信编程(10):Channel 和 Selector
java·开发语言
爱吃提升7 小时前
MATLAB impulse函数脉冲响应完整实操教程
开发语言·matlab
小饕7 小时前
从 1080 Ti 到树莓派 4:Qwen2.5-0.5B Function Calling 端侧部署七步实战
开发语言·人工智能
糯米导航7 小时前
Rust + ONNX Runtime 构建生产级 AI 推理服务:从零到压测
开发语言·人工智能·rust