C#相对于C++的好处之一是:有属性这个东西,直接能够让你使用,而且得到语法的支持,首先我们来看看C#中如何表示一个属性,例如:
class MyClass
{
private string myName = string.Empty;
public MyName
{
get{return myName;}
set{myName = value;}
}
}
好了,现在我们可以使用如下的方法来访问属性:
MyClass myClass;
myClass.MyName ="dddd";
这是最普通的方式,另外一种方式就是使用AttributeUsage来定义一个属性类,就象系统里面提供的属性一样。
定义自己的属性类需要从System.Attribute这个类继承,然后使用上面的方法来定义属性,例如:
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
class MyAttribute:Attribute
{
public MyAttribute(string name)
{
MyName = name;
}
private string myName = string.Empty;
public MyName
{
get{return myName;}
set{myName = value;}
}
}
这个属性的使用不同于上面,首先我们需要定义一个类,例如:
[MyAttribute (“MyName is Test”)]
class MyClass
{
}
[MyAttribute (“MyName is Test”)]实际上构造一个属性,MyName是指定的内容;但这个属性并不执行,而是在有代码调用MyClass的GetType的GetCustomAttribute的时候才真正的建立代码。
其实这种属性是使用反射机制,为类在运行时保存一些信息,下面是一个使用自定义属性的例子:
using System;
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,
AllowMultiple=true)]
public class Author : Attribute
{
public Author(string name)
{
this.name = name; version = 1.0;
}
public double version;
string name;
public string GetName()
{
return name;
}
}
[Author("H. Ackerman")]
class FirstClass
{
/*...*/
}
class SecondClass // 没有定义Author属性
{
/*...*/
}
[Author("H. Ackerman"), Author("M. Knott", version=1.1)]
class Steerage
{
/*...*/
}
class AuthorInfo
{
public static void Main()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(Steerage));
}
public static void PrintAuthorInfo(Type t)
{
Console.WriteLine("Author information for {0}", t);
Attribute[] attrs = Attribute.GetCustomAttributes(t);
foreach(Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
Console.WriteLine(" {0}, version {1:f}",
a.GetName(), a.version);
}
}
}
}