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;
    }
}
相关推荐
苍狼唤32 分钟前
WinForm练习知识补充(多线程)
c#
2zcode44 分钟前
基于MATLAB图像处理的饮料瓶灌装液位检测系统设计与实现
开发语言·图像处理·matlab
必须得开心呀2 小时前
QT解决中文乱码问题
开发语言·qt
真鬼1232 小时前
【Unity WebGL】内嵌网页与双向通信
unity·游戏引擎·webgl
这不小天嘛3 小时前
JAVA八股——redis篇
java·开发语言·redis
逝水无殇4 小时前
C# 字符串(String)详解
开发语言·后端·c#
精明的身影4 小时前
C++自学之路1:Hello world
开发语言·c++
leo__5205 小时前
基于导航数据的扩展卡尔曼滤波(EKF)MATLAB 实现
开发语言·matlab
gugucoding5 小时前
25. 【C语言】二进制文件与随机读写
c语言·开发语言
北极星日淘5 小时前
中古货品品相评级算法实战|Java权重计分实现标准化五级品相体系
开发语言·python