using System;
using System.Reflection;
namespace Anytao.Net
{
// 特性應用於特性:控制自訂特性如何被應用
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class MyselfAttribute : Attribute
{
private string _name;
private int _age;
private string _memo;
public MyselfAttribute() { }
public MyselfAttribute(string name, int age) { _name = name; _age = age; }
// 特性的屬性(注意:特性 ≠ 屬性)
public string Name { get { return _name ?? string.Empty; } }
public int Age { get { return _age; } }
public string Memo { get { return _memo; } set { _memo = value; } }
public void ShowName() => Console.WriteLine("Hello, {0}", _name ?? "world.");
}
// 應用自訂特性:可用 Myself 或 MyselfAttribute,可設定屬性 Memo
[Myself("Emma", 25, Memo = "Emma is my good girl.")]
public class MyTest
{
public void SayHello() => Console.WriteLine("Hello, my .Net world.");
}
public class MyRun
{
public static void Main()
{
// 反射取得特性資訊
Type tp = typeof(MyTest);
MemberInfo info = tp;
MyselfAttribute attr = (MyselfAttribute)Attribute.GetCustomAttribute(info, typeof(MyselfAttribute));
if (attr != null)
{
Console.WriteLine("Name: {0}", attr.Name);
Console.WriteLine("Age: {0}", attr.Age);
Console.WriteLine("Memo of {0} is {1}", attr.Name, attr.Memo);
attr.ShowName(); // Hello, Emma
}
// 反射建立實例並呼叫方法
object obj = Activator.CreateInstance(typeof(MyTest));
MethodInfo mi = tp.GetMethod("SayHello");
mi.Invoke(obj, null); // Hello, my .Net world.
Console.ReadLine();
}
}
}
Attribute 是 .NET 引入的標誌性技術:
System.AttributeAttribute 結尾,使用時可省略深入掌握 Attribute,能解鎖 .NET 元程式設計、AOP、框架開發的核心能力。