【转】c#自定义属性的示例

什么是自定义属性呢?
用过Web Service的人都会知道这样一个标记[WebMethod]
在方法,属性,类,结构等的前面加上形如“[xxx]”的标记,就可能用C#的反射技术读取这个标记。
其中xxx是继承自System.Attribute的类

由此可见,自定义属性可以用来标记某个类或方法是否具有某种属性,典型的应用就是[Serializable],[WebMethod]。

好的,来看一段代码:
[code]
using System;
using System.Reflection;
class Program
{
static void Main()
{
System.Attribute[] attrs = Attribute.GetCustomAttributes(typeof(xxx));
foreach (System.Attribute attr in attrs)
{
if (attr is aaa)
{
aaa a = (aaa)attr;
Console.WriteLine("name={0},version={1}",a.Name,a.Version);
}
}
}
}
[aaa("nid",Version=1)]
public class xxx
{
//...
}
public class aaa : Attribute
{
public aaa(string name)
{
this.name = name;
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int version;
public int Version
{
get { return version; }
set { version = value; }
}
}[/code]

来自:http://www.ljnid.cn/?id=270

posted @ 2009-12-31 14:03  s80895304  阅读(354)  评论(0编辑  收藏  举报