新建解决方案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); } } } } } } |