下面的代码定义了一个名字为widebright的自定义的属性,然后还有测试使用的例子,用到了“反射”了,其实我也接触不多“反射”这个东西,就是个提供运行时获取类结构等的支持的东西了,还可以用来动态加载库等,好像。usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Reflection;namespaceWindowsFormsApplication1
{//这里利用AttributeUsage 来设置我们的自定义属性的应用范围,这里定义的可以用于类,结构和方法的声明
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct |AttributeTargets.Method,
AllowMultiple= true)] //multiuse attribute
class widebright : Attribute //从Attribute 继承,写一个自定义属性
{private stringstrname;public widebright(stringname)
{
strname=name;
}//添加一个允许外部访问的属性
public stringName
{get { returnstrname; }set { strname =Name; }
}
}//写一个测试类
[widebright("widebright")]classwidebrightTestClass
{private string name = "hahaa";
[widebright("test1")]public voidTestMethod()
{
System.Console.WriteLine("哈哈,第一个测试通过");
}
[widebright("test2")]public void TestMethod2(stringparm)
{
System.Console.WriteLine("哈哈,第二个测试通过,传过来的参数是:{0}", parm);
}public voidTestMethod3()
{
System.Console.WriteLine("哈哈,第三个测试,name的值为{0}", this.name);
}
}public partial classForm1 : Form
{publicForm1()
{
InitializeComponent();
}private void Form1_Load(objectsender, EventArgs e)
{
widebrightTestClass testClass= newwidebrightTestClass();//在程序运行时,获取自己添加进去的“自定义属性”
Type type =testClass.GetType();
testClass.TestMethod3 ();//利用反射 运行时修改对象的私有属性
BindingFlags flags = (BindingFlags.NonPublic |BindingFlags.Instance);
type.GetField ("name",flags ).SetValue (testClass,"widebright");//再次调用方法,应该可以看到name私有属性确实被修改成widebright了
testClass.TestMethod3 ();foreach (Attribute attr in type.GetCustomAttributes(false))
{if (attr.GetType() == typeof(widebright))
{
System.Console.WriteLine("testClass 对象具有 widebrihgt这个自定义属性");
}
}//测试 widebright”自定义属性“时候存在,获取type的所有方法
foreach (MethodInfo mInfo intype.GetMethods())
{foreach (Attribute attr inAttribute.GetCustomAttributes(mInfo))
{//Check for the AnimalType attribute.
if (attr.GetType() == typeof(widebright))
{
Console.WriteLine("{0}方法有一个 名字为{1} 的\"widebright\" 属性.",
mInfo.Name, ((widebright)attr).Name );if (((widebright)attr).Name == "test2")
{//动态调用testClass对象的方法
mInfo.Invoke(testClass, new string[] {((widebright)attr).Name});
}else{//第一个方法没有参数,所以传个null给他
mInfo.Invoke (testClass, null);
}
}else{
Console.WriteLine("{0}方法不具有\"widebright\" 属性.",
mInfo.Name );
}
}
}
}
}
运行程序后将打印:
哈哈,第三个测试,name的值为hahaa
哈哈,第三个测试,name的值为widebright
testClass 对象具有 widebrihgt这个自定义属性
TestMethod方法有一个 名字为test1 的"widebright"属性.
哈哈,第一个测试通过
TestMethod2方法有一个 名字为test2 的"widebright"属性.
哈哈,第二个测试通过,传过来的参数是:test2
很有意思用法,呵呵, widebright手记