zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA
    leetcode刷题笔记 222题 完全二叉树的节点个数
    leetcode刷题笔记 221题 最大正方形
    leetcode刷题笔记 220题 存在重复元素 III
    leetcode刷题笔记 219题 存在重复元素 II
    leetcode刷题笔记 218题 天际线问题
    leetcode刷题笔记 216题 组合总和 III
  • 原文地址:https://www.cnblogs.com/godcity/p/2508461.html
Copyright © 2011-2022 走看看