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;
    }
}
相关推荐
SEO_juper8 小时前
2026年用Python分析网站访问日志:看清Googlebot和AI爬虫怎么爬你的站(附完整代码)
开发语言·前端·seo·独立站·谷歌优化
Java的搬运工8 小时前
使用 C# 轻松管理 PDF 文件的用户权限
c#·用户权限
邪修king8 小时前
Re:Linux 系统篇(二十九):动静态库Chapter2:动态库深度辨析 —— 核心本质、制作流程、双阶段查找模型与排错指南
android·java·linux·开发语言
泡海椒9 小时前
告别 iText 繁杂配置:jquick-pdf 极简 PDF 生成实战(零基础上手)
java·开发语言·pdf
玖玥拾18 小时前
Unity Shader 基础与图形学(一)
unity·图形渲染·图形学·shader
君顾120 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到落地部署
java·开发语言·健身房
香菜TTT20 小时前
大模型上下文协议(MCP):AI 应用的“USB-C”接口技术
开发语言·人工智能·经验分享
aramae21 小时前
模拟实现strlen()函数 (C语言)
c语言·开发语言·后端
Neil201321 小时前
ajax跨域请求
c#
唐青枫1 天前
别把 Razor 当成几段 HTML:C#.NET Razor Pages、MVC 视图与实战详解
c#·.net