自定义Attribute【简单源码示例】
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
namespace TestSpace
{
//1)制作标签
public class FriutTypeAttribute : Attribute
{
public string Note
{
get { return "所有有苹果都我家种的!"; }
}
}
[FriutType] //2)贴标签
public class Apple
{
private string _color;
public Apple(string color) { _color = color; }
public string Color
{
get { return _color; }
}
}
class DemoClass
{
static void Main(string[] args)
{
Apple a = new Apple("红色");
Console.WriteLine("苹果的颜色是:{0} ", a.Color);
//3)查看标签上的信息
Type type = a.GetType();
foreach (Attribute attr in Attribute.GetCustomAttributes(type))
{
if (attr.GetType() == typeof(FriutTypeAttribute))
Console.WriteLine("显示Apple的相关信息: {0}", ((FriutTypeAttribute)attr).Note);
}
Console.ReadLine();
}
}
}
1) 先写一个简单的普通的类,这个类里有一个属性 只不过这个标签类继承自Attribute
2) 将标签贴在需要描述的类上面
3) 遍历类实例上的所有的Attribute,如果其类型等于自己贴的标签类的类型,那么强制类型转换后输出所贴的标签的属性
原文:http://www.cnblogs.com/freebird92/archive/2006/12/27/605047.html
posted on 2010-05-11 17:33 Master zhu 阅读(179) 评论(0) 编辑 收藏 举报