using System;
using System.Collections.Generic;
using System.Text;
namespace 使用反射访问属性
{
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true)
]
public class Author : System.Attribute
{
string name;
public double heyu;
public double version;
//这里定义多少个变量,对应使用的地方都可以填
public Author(string name)
{
this.name = name;
version = 1.0; // Default value
heyu = 1;
}
public string GetName()
{
return name;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace 使用反射访问属性
{
[Author("H. FirstClass")]
public class FirstClass
{
// ...
}
// No Author attribute
public class SecondClass
{
// ...
}
// [Author("H. ThirdClass"), Author("M. Knott", heyu = 1, version = 2.0)]
//以上等效于下面
[Author("H. ThirdClass")]
[Author("M. Knott", heyu = 1, version = 2.0)]
public class ThirdClass
{
// ...
}
}
using System;
using System.Windows.Forms;
namespace 使用反射访问属性
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // reflection
foreach (System.Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
// System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
MessageBox.Show(a.GetName().ToString() + a.version.ToString());
}
}
}
}
}