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 分钟前
YOLO26-OBB ONNXruntime部署 python/C++
开发语言·c++·python
小曹要微笑6 分钟前
C#的运算符重载
开发语言·c#·运算符重载·c#运算符重载
我是唐青枫7 分钟前
C#.NET Channel 深入解析:高性能异步生产者消费者模型实战
开发语言·c#·.net
Ivanqhz9 分钟前
活跃范围重写(Live Range Rewriting)
开发语言·c++·后端·算法·rust
Crazy Struggle10 分钟前
C# + ViewFaceCore 快速实现高精度人脸识别
c#·人脸识别·.net·开源项目
人道领域12 分钟前
【绝对干货】C语言常量,变量,内存全方位总结:从入门到精通,这一篇就够了!
c语言·开发语言
yuyuxun113 分钟前
基于JSP购物网站系统的设计与实现 毕业设计-附源码03645
java·开发语言·python·django·flask·课程设计·pygame
小曹要微笑17 分钟前
委托(Delegate)在C#中的概念与应用
前端·javascript·c#
牢七23 分钟前
Slim-4.x php审计 报错分析
android·开发语言·ide·安全·php
认真的小羽❅36 分钟前
JavaScript完全指南:从入门到精通
开发语言·javascript·ecmascript