自定义属性的应用

作者在 2008-06-02 14:09:39 发布以下内容
新建解决方案WindowsFormsApplication1
新建类MyAttribute
using System;
namespace WindowsFormsApplication1
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public class MyAttribute : Attribute
    {
        private string _value;
        public string Value
        {
            get
            {
                return _value;
            }
        }
        public MyAttribute(string value)
        {
            _value = value;
        }
    }
}
窗体代码
using System;
using System.Reflection;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    [MyAttribute("HEYU5220")]//自定义属性
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Type[] types = Assembly.GetExecutingAssembly().GetTypes();
            foreach (Type t in types)
            {
                object[] attributes = t.GetCustomAttributes(typeof(MyAttribute), true);
                foreach (object obj in attributes)
                {
                    MyAttribute attribute = (MyAttribute)obj;
                    if (!string.IsNullOrEmpty(attribute.Value))
                    {
                        MessageBox.Show(attribute.Value);
                    }
                }
            }
        }
    }
}
 
组件 | 阅读 3844 次
文章评论,共0条
游客请输入验证码
浏览24974次