您现在的位置是:首页 > 数码 > 

特性入门AttributeUsage

2025-07-17 22:28:35
特性入门AttributeUsage msdn:ms-help://MS.MSDQTR.200FEB.2052/csspec/html/vclrfcsharpspec_17_1_1.htm  AttributeUsage 属性(第 17.4.1 节)用于描述使用属性类的方式。 AttributeUsage 具有一个定位参数(第 17

特性入门AttributeUsage

msdn:ms-help://MS.MSDQTR.200FEB.2052/csspec/html/vclrfcsharpspec_17_1_1.htm 

AttributeUsage 属性(第 17.4.1 节)用于描述使用属性类的方式。

AttributeUsage 具有一个定位参数(第 17.1.2 节),该参数使属性类能够指定自己可以用在那种声明上。示例

using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class SimpleAttribute: Attribute 
{...
}

定义了一个名为 SimpleAttribute 的属性类,此属性类只能放在类声明和接口声明上。示例

[Simple] class Class1 {...}
[Simple] interface Interface1 {...}

显示了 Simple 属性的几种用法。虽然此属性是用名称 SimpleAttribute 定义的,但在使用时可以省略 Attribute 后缀,从而得到简称 Simple。因此,上例在语义上等效于:

[SimpleAttribute] class Class1 {...}
[SimpleAttribute] interface Interface1 {...}

AttributeUsage 还具有一个名为 AllowMultiple 的命名参数(第 17.1.2 节),此参数用于说明对于某个给定实体,是否可以多次使用该属性。如果属性类的 AllowMultiple 为 true,则此属性类是多次性属性类,可以在一个实体上多次被应用。如果属性类的 AllowMultiple 为 false 或未指定的,则此属性类是一次性属性类,在一个实体上最多只能使用一次。

示例

using System;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AuthorAttribute: Attribute
{ private string name;public AuthorAttribute(string name) { = name;}public string ame { get { return name; } }
}

定义了一个名为 AuthorAttribute 的多次性属性类。示例

[Author(Brian Kernighan), Author(Dennis Ritchie)] 
class Class1
{...
}

显示了一个两次使用 Author 属性的类声明。

AttributeUsage 具有另一个名为 Inherited 的命名参数,此参数指示在基类上指定该属性时,该属性是否也会被从此基类派生的类所继承。如果属性类的 Inherited 为 true,则该属性会被继承。如果属性类的 Inherited 为 false 或者未指定,那么该属性不会被继承。

没有附加 AttributeUsage 属性的属性类 X,例如

using System;
class X: Attribute {...}

等效于下面的内容:

using System;
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)
]
class X: Attribute {...}

#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格

本文地址:http://www.dnpztj.cn/shuma/794858.html

相关标签:无
上传时间: 2024-01-10 12:11:15
留言与评论(共有 8 条评论)
本站网友 扬子石化爆炸
24分钟前 发表
如果属性类的 Inherited 为 false 或者未指定,那么该属性不会被继承
本站网友 德黑兰机场
9分钟前 发表
虽然此属性是用名称 SimpleAttribute 定义的,但在使用时可以省略 Attribute 后缀,从而得到简称 Simple
本站网友 南沙二手房
15分钟前 发表
AttributeUsage 具有一个定位参数(第 17.1.2 节),该参数使属性类能够指定自己可以用在那种声明上
本站网友 朱可
11分钟前 发表
因此,上例在语义上等效于: [SimpleAttribute] class Class1 {...} [SimpleAttribute] interface Interface1 {...} AttributeUsage 还具有一个名为 AllowMultiple 的命名参数(第 17.1.2 节),此参数用于说明对于某个给定实体,是否可以多次使用该属性
本站网友 悔恨的讯息
6分钟前 发表
Attribute {...} 等效于下面的内容: using System; [AttributeUsage(AttributeTargets.All
本站网友 艾利斯顿大学
15分钟前 发表
示例 using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SimpleAttribute
本站网友 新江湾城公园
11分钟前 发表
如果属性类的 Inherited 为 false 或者未指定,那么该属性不会被继承