C#-WinForm-设计时编程【3】-自定义特性

自定义特性的使用一般需要反射的支持,一般在自定义属性、自定义控件、单元测试中经常用到。

第一步:要使用自定义特性,需要先定义一个自定义特性类——

 1     class MyAttribute : Attribute
 2     {
 3         public MyAttribute(string msg)
 4         {
 5             this.msg = msg;
 6         }
 7 
 8         protected string msg;
 9         public string Msg
10         {
11             get
12             {
13                 return msg;
14             }
15             set
16             {
17                 msg = value;
18             }
19         }
20     }

 

 第二步:然后定义一个类,在类中使用该特性——

1     [MyAttribute("我是类属性哦")]
2     class MyContainer : ContainerControl
3     {
4         [MyAttribute("我是构造函数属性哦")]
5         public MyContainer()
6         {
7 
8         }
9     }

 

 第三步:通过反射类,获取自定义特性来进行相应的操作——

 1     public partial class Form1 : Form
 2     {
 3         public Form1()
 4         {
 5             InitializeComponent();
 6 
 7             MyContainer myContainer = new MyContainer();
 8             Type type = myContainer.GetType();
 9 
10             foreach (Attribute attr in Attribute.GetCustomAttributes(type))
11             {
12                 if (attr.GetType() == typeof(MyAttribute))
13                 {
14                      MessageBox.Show(((MyAttribute)attr).Msg);
15                 }
16             }
17 
18             foreach (System.Reflection.ConstructorInfo ci in type.GetConstructors())
19             {
20                 foreach (Attribute attr in Attribute.GetCustomAttributes(ci))
21                 {
22                     if (attr.GetType() == typeof(MyAttribute))
23                     {
24                         MessageBox.Show(((MyAttribute)attr).Msg);
25                     }
26                 }
27             }
28         }
29     }

 

posted @ 2012-05-18 23:34  上帝之城  阅读(391)  评论(0编辑  收藏  举报