3 回答

TA貢獻1911條經驗 獲得超7個贊
在屬性構造函數內設置調試器斷點,并編寫一些反射代碼以讀取那些屬性。您會注意到,只有從relfection API返回屬性對象后,才能創建屬性對象。屬性是每個類的。它們是元數據的一部分。
看看這個:
Program.cs
using System;
using System.Linq;
[My(15)]
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Program started");
var ats =
from a in typeof(Program).GetCustomAttributes(typeof(MyAttribute), true)
let a2 = a as MyAttribute
where a2 != null
select a2;
foreach(var a in ats)
Console.WriteLine(a.Value);
Console.WriteLine("Program ended");
Console.ReadLine();
}
}
MyAttribute.cs
using System;
[AttributeUsage(validOn : AttributeTargets.Class)]
public class MyAttribute : Attribute
{
public MyAttribute(int x)
{
Console.WriteLine("MyAttribute created with {0}.", x);
Value = x;
}
public int Value { get; private set; }
}
結果
Program started
MyAttribute created with 15.
15
Program ended
但不必擔心屬性構造函數的性能。它們是反思的最快部分:-P
- 3 回答
- 0 關注
- 520 瀏覽
添加回答
舉報