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;
    }
}
相关推荐
不吃土豆的马铃薯4 分钟前
高性能服务器程序框架详解(包括Reactor,有限状态机等)
linux·服务器·开发语言·网络·c++
Shadow(⊙o⊙)6 分钟前
库的制作与原理1.0,库打包,协作,目标文件.o、ELF格式。
linux·运维·服务器·开发语言
wyc是xxs6 分钟前
用纯 Node.js 写了一个 JS 解释器 — kernel-js-lite
开发语言·javascript·npm·node.js
hai3152475437 分钟前
AI工业化编程的黎明:由逻辑压缩到知识融合的范式跃迁
开发语言·人工智能·线性代数·机器学习·数学建模·概率论
Cloud_Shy61814 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第一章 Item 7 - 9)
开发语言·数据库·python
এ慕ོ冬℘゜15 分钟前
从零封装企业级通用确认弹窗组件|高复用、低耦合、适配全场景
开发语言·前端·javascript
郝学胜-神的一滴16 分钟前
Qt 高级开发 020:水平布局手写代码实战
开发语言·c++·qt·系统架构·软件构建·用户界面
小拉达不是臭老鼠22 分钟前
Unity中的UI系统之UGUI_登陆面板实现
ui·unity
Mortalbreeze23 分钟前
C++11 ---- 右值引用、值类型
开发语言·c++
少司府24 分钟前
C++进阶:多态
c语言·开发语言·c++·多态·抽象类·虚函数·虚表指针