代码如下,说明在注释里面。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace wlf.net
{
//定制特性也可以应用到其它定制特性上,
//应用AttributeUsage,来控制如何应用新定义的特性。
[AttributeUsage(AttributeTargets.All,//可应用所有元素
AllowMultiple = true,//允许应用多次
Inherited = false)]//不继承到派生类
//特性也是一个类
//必须集成System.Attribute类。
//命名规范为:"类名"+Attribute.
public class MySelfAttribute : Attribute
{
//定义字段
private string _name;
private int _age;
private string _memo;
//必须定义构造函数,如果不定义有编译器提供的无参默认构造函数
public MySelfAttribute()
{
}
public MySelfAttribute(string name, int age)
{
_name = name;
_age = age;
}
//定义属性
//显然特性和属性不是一回事儿
public string Name
{
get { return _name == null ? string.Empty : _name; }
}
public int Age
{
get { return _age; }
}
public string Memo
{
get { return _memo; }
set { _memo = value; }
}
//定义方法
public void ShowName()
{
Console.WriteLine("Hello ,{0}", _name == null ? "world." : _name);
}
}
//应用自定义特性
//可以以MySelf或者MySelfAttribute作为特性名
//可以给属性Memo 赋值
[MySelf("wlf", 21, Memo = "wlf is My self.")]
public class Mytest
{
public void SayHello()
{
Console.WriteLine("Hello,my.net world.");
}
}
public class MyRun
{
public static void Main(String[] args)
{
//如何以反射确定特性信息
Type tp = typeof(Mytest);
MemberInfo info = tp;
MySelfAttribute myAttribute = (MySelfAttribute)Attribute.GetCustomAttribute(info, typeof(MySelfAttribute));
if (myAttribute != null)
{
//嘿嘿,在运行是查看注释内容,是不是很爽啊。
Console.WriteLine("Name:{0}", myAttribute.Name);
Console.WriteLine("Age:{0}", myAttribute.Age);
Console.WriteLine("Memo of {0} is {1}", myAttribute.Name, myAttribute.Memo);
myAttribute.ShowName();
//多点反射
object obj = Activator.CreateInstance(typeof(Mytest));
MethodInfo mi = tp.GetMethod("SayHello");
mi.Invoke(obj, null);
Console.Read();
}
}
}
}