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;
    }
}
相关推荐
招风的黑耳2 分钟前
Java集合框架详解与使用场景示例
java·开发语言
xrkhy4 分钟前
java中XML的使用
xml·java·开发语言
抽风的雨6107 分钟前
【python基础知识】Day 27 函数专题2:装饰器
开发语言·python
Zhen (Evan) Wang14 分钟前
ABP-Book Store Application中文讲解 - Part 2: The Book List Page
c#
martian6651 小时前
医学影像系统性能优化与调试技术:深度剖析与实践指南
开发语言·系统安全·dicom
y102121041 小时前
Pyhton训练营打卡Day27
java·开发语言·数据结构
AA-代码批发V哥1 小时前
Java类一文分解:JavaBean,工具类,测试类的深度剖析
java·开发语言
chilavert3181 小时前
从RPA项目说说RPC和MQ的使用。
开发语言·qt·rpc·rabbitmq
小乖兽技术2 小时前
在 .NET 8 开发的WinForms 程序中展示程序版本号的几种方式
开发语言·c#·.net
zyhomepage2 小时前
科技的成就(六十八)
开发语言·人工智能·科技·算法·内容运营