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;
    }
}
相关推荐
啊吧怪不啊吧19 分钟前
C++之基于正倒排索引的Boost搜索引擎项目usuallytool部分代码及详解
开发语言·c++·搜索引擎·项目
CeshirenTester1 小时前
9B 上端侧:多模态实时对话,难点其实在“流”
开发语言·人工智能·python·prompt·测试用例
发现你走远了1 小时前
Windows 下手动安装java JDK 21 并配置环境变量(详细记录)
java·开发语言·windows
游乐码1 小时前
c#类和对象
开发语言·c#
黎雁·泠崖2 小时前
Java常用类核心详解(一):Math 类超细讲解
java·开发语言
懒惰成性的2 小时前
12.Java的异常
java·开发语言
-To be number.wan2 小时前
Python数据分析:时间序列数据分析
开发语言·python·数据分析
前路不黑暗@3 小时前
Java项目:Java脚手架项目的通用组件的封装(六)
java·开发语言·spring
马士兵教育3 小时前
程序员简历如何编写才能凸显出差异化,才能拿到更多面试机会?
开发语言·后端·面试·职场和发展·架构
jz_ddk4 小时前
[指南] Python循环语句完全指南
开发语言·python·continue·循环·for·while·break