using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace prjAttribute
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Button1_Click(object sender, EventArgs e)
{
label1.Text += typeof(Button) + "\n";
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
//Type 是的根據System.Reflection功能主要的方法來存取中繼資料。
//使用的成員Type取得型別宣告,成員的類型(例如建構函式、 方法、 欄位、 屬性和事件的類別)
//的詳細資訊,以及模組和組件部署所在的類別。
private void PrintAuthorInfo(Type t)
{
label1.Text += $"Author information for {t}"+ "\n";
//System.Console.WriteLine("Author information for {0}", t);
// Using reflection.
//取得type上的裝飾(特性Attribute),可能很多個所以用陣列
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // Reflection.
// Displaying output.
foreach (System.Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
//取的該Attribute的屬性
label1.Text += string.Format(" {0}, version {1:f}", a.GetName(), a.version) + "\n";
// System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
}
}
}
// Multiuse attribute.
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // Multiuse attribute.
]
public class Author : System.Attribute
{
string name;
public double version;
public Author(string name)
{
this.name = name;
// Default value.
version = 1.0;
}
public string GetName()
{
return name;
}
}
// Class with the Author attribute.
[Author("P. Ackerman")]
public class FirstClass
{
// ...
}
// Class without the Author attribute.
public class SecondClass
{
// ...
}
// Class with multiple Author attributes.
[Author("P. Ackerman"), Author("R. Koch", version = 2.0)]
public class ThirdClass
{
// ...
}
}
}