AttributeUsage

本文详细介绍了C#中的特性(Attribute)概念,包括如何使用AttributeUsage定义特性目标、允许多个相同特性及指定继承规则等内容,并通过实例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文整理自网络。

         首先你得理解什么是Attribute(这里翻译为特性,属性应该对应于(Property),是c#另一个内容了),特性允许我们添加类似关键字(比如public)的批注来为元素(可以是class,method,property,parameter,event等),在运行时可以通过反射获得这些信息,从而影响程序的行为。

        对于Attribute,我们可以使用AttributesUage施加在这些特性(attribute)之上。我们姑且可以称AttributeUsage为元特性(专门施加在特性之上的特性)

      [AttributeUsage(     validon,     AllowMultiple = allowmultiple,     Inherited = inherited)] 

     例如:[AttributeUsage(AttributeTargets.Class, AllowMultiple = true,  Inherited = true)]//注意后面两个参数必须以具名参数的方式给出,不能直接写true,false。


      下面分别讲解这三个参数:


一、validon

定义特性目标

 1public enum AttributeTargets
 2{
 3    Assembly    = 0x0001,
 4    Module      = 0x0002,
 5    Class       = 0x0004,
 6    Struct      = 0x0008,
 7    Enum        = 0x0010,
 8    Constructor = 0x0020,
 9    Method      = 0x0040,
10    Property    = 0x0080,
11    Field       = 0x0100,
12    Event       = 0x0200,
13    Interface   = 0x0400,
14    Parameter   = 0x0800,
15    Delegate    = 0x1000,
16    All = Assembly │ Module │ Class │ Struct │ Enum │ Constructor │ 
17        Method │ Property │ Field │ Event │ Interface │ Parameter │ 
18        Delegate,
19
20    ClassMembers  =  Class │ Struct │ Enum │ Constructor │ Method │ 
21        Property │ Field │ Event │ Delegate │ Interface,
22}
23

       当使用Attribute特性时,我们有时需要指定这些特性施加的目标类型AttributeTargets。我们给定AttributeTargets.Class,因此特性只能被附加到类类型上。若未指定AttributeUsage特性,缺省值是AttributeTargets.All。特性AttributeTargets用来限制特性使用范围。


 1[AttributeUsage(AttributeTargets.Class)]
 2public class RemoteObjectAttribute : Attribute
 3{
 4
 5}
 6
 7[AttributeUsage(AttributeTargets.Method)]
 8public class TransactionableAttribute : Attribute
 9{
10
11
12
13}
14

 可以使用或(|)操作符组合特性目标枚举中列出的项。

 单一用途和多用途特性

        可以使用AttributeUsage定义特性的单一用途或多用途,即确定在某个类型上使用某一特性的次数。在缺省情况下,所有特性都是单用途的。在AttributeUsage特性中,指定AllowMultiple为true,则允许特性多次附加到指定的类型上。例如:

 1[AttributeUsage(AttributeTargets.All, AllowMultiple=true)]
 2public class SomethingAttribute : Attribute
 3{
 4    public SomethingAttribute(String str)
 5    {
 6    }
 7}
 8
 9     [Something("abc")]
10[Something("def")]
11class MyClass
12{
13}
14

 

指定继承特性规则

      在AttributeUsageAttribute特性的最后部分是继承标志,指示父类的某个特性是否能被子类继承。缺省值是false。当该参数为FALSE时,一切都很容易理解。然而,若继承标志被设置为true,它的含义将依赖于AllowMultiple标志的值。(原文这里讲的并不清楚)

      若继承标志被设置为true,AllowMultiple标志是false,则子类该类型特性将覆盖父类该类型特性。

     若继承标志被设置为true,AllowMultiple标志是true,则父类该特性的成员与子类同类型特性的成员同时存在于子类。

范例:

 1using System;
 2using System.Reflection;
 3
 4namespace AttribInheritance
 5{
 6    [AttributeUsage(
 7        AttributeTargets.All, 
 8        AllowMultiple = true,
 9        //AllowMultiple = false,
10        Inherited = true
11    )]
12    public class SomethingAttribute : Attribute
13    {
14        private string name;
15        public string Name
16        
17            get return name; }
18            set { name = value; }
19        }
20
21        public SomethingAttribute(string str)
22        {
23            this.name = str;
24        }
25    }
26
27     [Something("MyClass")]
28    class MyClass
29    {
30    }
31
32    [Something("Another")]
33    class Another : MyClass
34    {
35    }
36
37    class Test
38    {
39        [STAThread]
40        static void Main(string[] args)
41        {
42            Type type =   Type.GetType("AttribInheritance.Another");//获取Another的类型信息
44            foreach (Attribute attr in type.GetCustomAttributes(true))//获取自定义特性,true表示也获取继承的特性。
46            {
47                SomethingAttribute sa =    attr as SomethingAttribute;//类型转换
49                if (null != sa)
50                {
51                     Console.WriteLine(sa.Name);
54                }
55            }
56
57        }
58    }
59}
60

若AllowMultiple设置为false,结果是:

Another

 若AllowMultiple设置为true,结果是:

MyClass

Another

原文地址:

http://www.cnblogs.com/stzyw/archive/2005/10/07/249693.html

参考文献:

《C# 4.0权威指南》

http://bbs.youkuaiyun.com/topics/360111279

using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; public class SkillHandler { // 用字典缓存方法委托 private static readonly Dictionary<string, Action<ISkill, IGuestData, GameObject>> _skillActions = new Dictionary<string, Action<ISkill, IGuestData, GameObject>>(StringComparer.OrdinalIgnoreCase); // 静态构造函数初始化字典 static SkillHandler() { var methods = typeof(SkillHandler).GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (var method in methods) { // 通过自定义特性过滤技能方法 var attr = method.GetCustomAttribute<SkillMethodAttribute>(); if (attr != null) { var action = (Action<ISkill, IGuestData, GameObject>)Delegate.CreateDelegate( typeof(Action<ISkill, IGuestData, GameObject>), method); _skillActions[attr.SkillName] = action; } } } public static void Execute(ISkill skill, IGuestData guestData, GameObject targetObj) { if (_skillActions.TryGetValue(skill.SkillName, out var action)) { action(skill, guestData, targetObj); } else { Debug.LogError($"未找到技能处理函数: {skill.SkillName}"); } } // 通过特性标记技能方法 [SkillMethod("Fireball")] public static void Fireball(ISkill skill, IGuestData guestData, GameObject target) { Debug.Log($"火球术逻辑: {target.name}"); } [SkillMethod("Heal")] public static void Heal(ISkill skill, IGuestData guestData, GameObject target) { //Debug.Log($"治疗术逻辑: {guestData.HP}"); } } // 自定义特性类 [AttributeUsage(AttributeTargets.Method)] public class SkillMethodAttribute : Attribute { public string SkillName { get; } public SkillMethodAttribute(string skillName) { SkillName = skillName; } } 详细讲解,每一行代码都要说
最新发布
07-20
/// <summary> /// Represents the position of an RFID reader. /// </summary> public class RfidReaderPos()//List<PlcPoint> plcPoints { /// <summary> /// Gets or sets the track number. /// </summary> public string RfidRdrlineCode { get; set; } /// <summary> /// Gets or sets the RFID code. /// </summary> public string RfidCode { get; set; } /// <summary> /// Gets or sets the 处理类型 division 分流 print 调用mes打印 /// </summary> public string RfidProcessType { get; set; } /// <summary> /// Gets or sets the RFID UID value. /// </summary> public string RfidUIDValue { get; set; } /// <summary> /// Gets or sets the RFID tag value. /// </summary> public string RfidTagValue { get; set; } /// <summary> /// Gets or sets the RFID data value. /// </summary> public string RfidDataValue { get; set; } /// <summary> /// Gets or sets the RFID data value timestamp. /// </summary> public string RfidDataValueTimestamp { get; set; } /// <summary> /// Gets or sets the RFID position code. /// </summary> public string RfidRdrpositionCode { get; set; } /// <summary> /// Gets or sets the RFID position name. /// </summary> public string RfidRdrpositionName { get; set; } /// <summary> /// Gets or sets the RFID position description. /// </summary> public string RfidRdrpositionDesc { get; set; } /// <summary> /// Gets or sets the RFID modbus slave ID. /// </summary> public int? RfidRdrSlaveId { get; set; } // 使用可空类型以对应可能的 null 值 public int RfidRdrpollIntervalMs { get; set; } = 50; public int RfidRdrtimeoutMs { get; set; } = 6000; /// <summary> /// Gets or sets the RFID modbus IP address. /// </summary> public string RfidRdrIp { get; set; } /// <summary> /// Gets or sets the RFID modbus port. /// </summary> public string RfidRdrPort { get; set; } /// <summary> /// Gets or sets the RFID protocol, specifically for modbus. /// </summary> public string RfidRdrProtocol { get; set; } /// <summary> /// 读写PLC点位列表(JSON 存储) /// </summary> public List<PlcPoint> PlcPoints { get; set; }//= plcPoints; public SemaphoreSlim ProcessingLock { get; set; } = new (1, 1); } 根据需要加入定义的注解: [AttributeUsage(AttributeTargets.Property)] public class SqliteField : Attribute { //public string DataType { get; set; } = "TEXT"; public bool IsPrimaryKey { get; set; } = false; public int Length { get; set; } public bool AutoIncrement { get; set; } public bool NotNull { get; set; } = false; } [AttributeUsage(AttributeTargets.Property)] public class MaxLengthAttr : Attribute { public int Length { get; } public MaxLengthAttr(int length) => Length = length; } [AttributeUsage(AttributeTargets.Property)] public class PrimaryKey : Attribute { }
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值