3 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
在屬性構(gòu)造函數(shù)內(nèi)設(shè)置調(diào)試器斷點(diǎn),并編寫一些反射代碼以讀取那些屬性。您會(huì)注意到,只有從relfection API返回屬性對象后,才能創(chuàng)建屬性對象。屬性是每個(gè)類的。它們是元數(shù)據(jù)的一部分。
看看這個(gè):
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; }
}
結(jié)果
Program started
MyAttribute created with 15.
15
Program ended
但不必?fù)?dān)心屬性構(gòu)造函數(shù)的性能。它們是反思的最快部分:-P
- 3 回答
- 0 關(guān)注
- 519 瀏覽
添加回答
舉報(bào)