Attribute:

公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型、字段、方法和属性等。Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。

在.NET中,Attribute被用来处理多种问题,比如序列化、程序的安全特征、防止即时编译器对程序代码进行优化从而代码容易调试等等。

使用Attribute的一般方式:

1)在程序集、类、域、方法等前面用[]表示;

2)可以带参数:位置参数(相当于构造方法带的参数)

命名参数(域名或属性名-值)

1.声明Attribute类:

因为attribute从System.Attribute继承而来,名字要用xxxAttribute格式,不然编译器不能识别。

2.使用Attribute类:

1)在类及成员上面使用方括号;

2)可以省略后最Attribute;

3.通过反射访问属性:

能够知道程序中的信息。

代码示例:

using System;
using System.Reflection; [AttributeUsage(AttributeTargets.Class
| AttributeTargets.Method ,
AllowMultiple = true)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
private string topic;
public string Topic // 属性 Topic 是命名参数
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url) // url 是位置参数
{
this.Url = url;
}
} [HelpAttribute("http://msvc/MyClassInfo", Topic="Test"),
Help("http://my.com/about/class")]
class MyClass
{
[Help("http;//my.com/about/method")]
public void MyMethod(int i)
{
return;
}
} public class MemberInfo_GetCustomAttributes
{
public static void Main()
{
Type myType = typeof(MyClass); //查看Attribute信息
object[] attributes = myType.GetCustomAttributes(false);
for (int i = ; i < attributes.Length; i ++)
{
PrintAttributeInfo(attributes[i]);
} MemberInfo[] myMembers = myType.GetMembers();
for(int i = ; i < myMembers.Length; i++)
{
Console.WriteLine("\nNumber {0}: ", myMembers[i]);
Object[] myAttributes = myMembers[i].GetCustomAttributes(false);
for(int j = ; j < myAttributes.Length; j++)
{
PrintAttributeInfo( myAttributes[j] );
}
}
} static void PrintAttributeInfo( object attr )
{
if( attr is HelpAttribute )
{
HelpAttribute attrh = (HelpAttribute) attr;
Console.WriteLine( "----Url: " + attrh.Url + " Topic: " + attrh.Topic );
Console.ReadKey(true);
}
}
}

最新文章

  1. PHP严重致命错误处理:php Fatal error: Cannot redeclare class or function
  2. C语言中关于对目录的操作
  3. 后缀数组---Milk Patterns
  4. Bootstrap页面布局24 - BS旋转木马功能
  5. Java笔记——面向切面编程(AOP模式)
  6. VC++创建、调用dll的方法步骤
  7. 9. memcpy() memccpy() memmove() strcpy() memset()
  8. 关于51单片机P0口的结构及上拉问题
  9. ThinkPHP - 关联模型 - 多对多
  10. python_如何对迭代器进行切片操作
  11. Install Windows 2016 on VirtualBox
  12. EntityFramework Core 2.1重新梳理系列属性映射(一)
  13. 跟踪mqttv3源码(一)
  14. Exploit-Exercises nebule 旅行日志(四)
  15. python主流测试框架的简介
  16. [JVM-1]Java运行时数据区域
  17. 【算法随记】Canny边缘检测算法实现和优化分析。
  18. How to make an IntelliJ IDEA plugin in less than 30 minutes
  19. springboot 前后端分离项目跨域配置
  20. 【Java】Java-ShutDownHook-优雅关闭系统资源

热门文章

  1. PADS_AD_Cadence转换
  2. [转]CISP(注册信息安全专业人员)认证(12天)
  3. Protobuf语言指南(转)
  4. HDU 4578 Transformation --线段树,好题
  5. NOIP2014pj子矩阵[搜索|DP]
  6. java io (一)
  7. LinkedList链式集合
  8. python黑客编程之端口爆破
  9. SuperSlidev2.1滑动门
  10. C#将JSON字符串对象序列化与反序列化