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;
    }
}
相关推荐
a17798877121 分钟前
小程序码的生成与获取码中的scene
小程序·c#
小邓的技术笔记6 分钟前
Python 入门:从“其他语言”到 Pythonic 思维的完整迁移手册
开发语言·python
啥咕啦呛12 分钟前
跟着AI学java第4天:面向对象编程巩固
java·开发语言·人工智能
聆风吟º12 分钟前
【C标准库】深入理解C语言memcmp函数:内存比较的利器
c语言·开发语言·库函数·memcmp
艾莉丝努力练剑14 分钟前
【Linux线程】Linux系统多线程(一):线程概念
java·linux·运维·服务器·开发语言·学习·线程
低保和光头哪个先来15 分钟前
Axios 近期安全版本
开发语言·前端·javascript·前端框架
无风听海17 分钟前
.NET10之C# Target-typed new expression深入解析
windows·c#·.net
chao18984418 分钟前
基于STM32F1的声源定位系统设计与实现
stm32·嵌入式硬件·unity
zzwq.19 分钟前
深入理解Python闭包与装饰器:从入门到进阶
开发语言·python
嵌入式学习菌23 分钟前
内网穿透全闭环实操指南
linux·开发语言·php