公共语言运行库允许开发人员添加类似关键字的描述性声明(称为特性)来批注编程元素如类型、字段、方法和属性等。特性与.net框架文件的元数据一起保存,并且可以用于向运行库描述代码或影响应用程序运行时的行为。
当声明从System.Attribute派生的特殊类的实例时,编译器创建特性。
.net框架出于多种原因使用特性并通过他们解决若干问题。特性可以描述如何序列化数据。指定用于强制安全性的特性以及限制实时(JIT just in time)编译器的优化以使代码易于调试。特性还可以记录文件名或代码作者,或在窗体开发阶段控制控件和成员的可见性。
自定义特性(本质上是直接或者间接从System.Attribute派生的传统类)的步骤:
1,应用AttributeUsageAttribute AttirbuteTargets枚举以及Inhertited(是否被继承)和AllowMultiple是否允许某元素存在多个此特性实例
2,声明特性类(必须为公共类;按照约定最好以Attribute结尾;间接或直接从SystemAttribute继承;VB中必须具有AtrributeUsageAttribute特性)
3,声明构造函数
4,声明属性
使用了特性后,可以使用Attribute.GetCustomAttribute和Attribute.GetCustomAttributes来检索特性的实例,同时结合类的MemberInfo 即GetMethods()返回的MemberInfo数组来检查类的成员是否含有特性
Are you interested in Data Engineering Essentials course on Kontext? Learn more
特性编程
info Last modified by Raymond 14 years ago
copyright
This page is subject to Site terms.
Log in with external accounts
timeline Stats
Page index
0.06
More from Kontext
Read Embedded Assembly Resource Files in .NET
visibility
1,287
thumb_up
0
access_time
10 months ago
Get Started on .NET 5 with Apache Spark
visibility
895
thumb_up
1
access_time
2 years ago
Resolve the Issues in Upgrading Entity Framework to Version 6.1
visibility
6,256
thumb_up
0
access_time
3 years ago