关键字(如 public 和 private)提供有关类成员的其他信息。另外,这些关键字通过描述类成员对其他类的可访问性来进一步定义类成员的行为。由于编译器被显式设计为识别预定义关键字,因此传统上您没有机会创建自己的关键字。但是,公共语言运行库允许您添加类似关键字的描述性声明(称为属性 (Attribute))来批注编程元素,如类型、字段、方法和属性 (Property)。
为运行库编译代码时,该代码被转换为 Microsoft 中间语言 (MSIL),并同编译器生成的元数据一起被放到可移植可执行 (PE) 文件的内部。属性 (Attribute) 使您得以向元数据中放置额外的描述性信息,并可使用运行库反射服务提取该信息。当您声明从 System.Attribute 派生的特殊类的实例时,编译器创建属性 (Attribute)。
.NET Framework 出于多种原因使用属性 (Attribute) 并通过它们解决若干问题。属性 (Attribute) 描述如何将数据序列化,指定用于强制安全性的特性,并限制实时 (JIT) 编译器的优化,从而使代码易于调试。属性 (Attribute) 还可以记录文件名或代码作者,或在窗体开发阶段控制控件和成员的可见性。
可使用属性 (Attribute) 以几乎所有可能的方式描述代码,并以富有创造性的新方式影响运行库行为。使用属性可以向 C#或其他任何以运行库为目标的语言添加自己的描述性元素,而不必重新编写编译器。
代码如下:
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace AtributeApplication
{
class Program
{
static void Main( string [] args)
{
Type type = typeof (SampleUserClass);
SampleAttribute attr = Attribute.GetCustomAttribute(type, typeof (SampleAttribute)) as SampleAttribute;
if (attr != null ){
Console.WriteLine(attr.Name);
Console.WriteLine(attr.Time.ToString());
Console.WriteLine(attr.Set.ToString() );
Console.WriteLine(attr.ToString());
Console.WriteLine( " ------------------ " );
}
object obj = Activator.CreateInstance( typeof (SampleUserClass));
MethodInfo methodInfo = type.GetMethod( " ShowInformation " );
methodInfo.Invoke(obj, null );
MethodInfo methodInfo2 = type.GetMethod( " DisplayInformation " );
string [] strs = { " 1 " , " 2 " , " 3 " };
methodInfo2.Invoke(obj,strs);
Console.ReadLine();
}
}
[AttributeUsage(AttributeTargets.All, Inherited = true , AllowMultiple = true )]
public class SampleAttribute : System.Attribute
{
private string _name;
private string _time;
private bool _set;
public SampleAttribute( string name, string time)
{
this ._name = name;
this ._time = time;
}
private SampleAttribute()
{
}
public string Name
{
get
{
return _name == null ? " name is null " :_name;
}
}
public string Time
{
get
{
return _time == null ? System.DateTime.Now.ToString():_time;
}
}
public bool Set
{
get
{
return _set ;
}
set
{
_set = value;
}
}
public override string ToString()
{
return string .Format( " {0}{1}{2} " , this .Name, this .Time.ToString(), this .Set.ToString());
}
}
[Sample( " XXXXX " , null, Set = true )]
public class SampleUserClass
{
public void ShowInformation()
{
Console.WriteLine( " XXXXXXXXXXXXXXXXXXXXXX " );
}
public void DisplayInformation( string para1, string para2, string para3) {
Console.WriteLine(para1 + " --- " + para2 + " ---- " + para3);
}
}
}
代码下载:特性源代码下载