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     }

 

转载于:https://www.cnblogs.com/godcity/archive/2012/05/18/2508461.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值