C#高级特性_Attribute

时间:2023-03-08 23:29:31
C#高级特性_Attribute

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