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;
    }
}
相关推荐
kaikaile199515 分钟前
C# 文件编码转换工具
开发语言·c#
沐雪轻挽萤30 分钟前
10. C++17新特性-保证的拷贝消除 (Guaranteed Copy Elision / RVO)
开发语言·c++
河阿里1 小时前
Java-JWT令牌技术深度指南
java·开发语言
小拉达不是臭老鼠1 小时前
Unity05_3D数学
学习·unity·游戏引擎
文静小土豆1 小时前
Java 应用上 K8s 全指南:从部署到治理的生产级实践
java·开发语言·kubernetes
西西弗Sisyphus1 小时前
Python 在终端里彩色打印
开发语言·python·print·彩色打印
Rsun045512 小时前
3、Java 工厂方法模式从入门到实战
java·开发语言·工厂方法模式
wjs20242 小时前
C++ 基本的输入输出
开发语言
码云数智-园园2 小时前
Python的GIL锁如何影响多线程性能?有哪些替代方案?
开发语言
咬_咬2 小时前
go语言学习(map)
开发语言·学习·golang·map