欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > C#自定义特性

C#自定义特性

2024/10/26 1:18:33 来源:https://blog.csdn.net/weixin_62613770/article/details/142885536  浏览:    关键词:C#自定义特性

特性的用处

一般用来影响某一个类的个别字段或者方法

定义特性

需要将类继承Attribute

可以通过构造函数的方式影响使用特性的方法

可以通过给自定义的特性通过加AttributeUsage特性的方法进行进一步管理

AttributeUsage特性默认传三个参数

第一个参数一般用来约束此自定义特性是否可以给类和字段使用

第二个参数若是为false,则不可以给一个类多个特性

若是为true则可以使用

第三个参数一般控制此自定义特性是否可以被继承

案例展示

在拓展类内部实现

    /// <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>();}

测试案例

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;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com