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;
    }
}
相关推荐
geovindu4 小时前
python: Memento Pattern
开发语言·python·设计模式·备忘录模式
学无止境_永不停歇4 小时前
十、C++多态
开发语言·c++
寻星探路4 小时前
【JVM 终极通关指南】万字长文从底层到实战全维度深度拆解 Java 虚拟机
java·开发语言·jvm·人工智能·python·算法·ai
Aric_Jones4 小时前
JavaScript 从入门到精通:完整语法指南
开发语言·javascript·ecmascript
岱宗夫up4 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
Dxy12393102164 小时前
中文乱码恢复方案
开发语言·python
浅念-5 小时前
C/C++内存管理
c语言·开发语言·c++·经验分享·笔记·学习
回敲代码的猴子5 小时前
2月8日上机
开发语言·c++·算法
rongyili885 小时前
Dify 外部知识库集成 Milvus 实战指南
开发语言·python·milvus
IT猿手6 小时前
MOEA/D(基于分解的多目标进化算法)求解46个多目标函数及一个工程应用,包含四种评价指标,MATLAB代码
开发语言·算法·matlab·多目标算法