2 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
您需要GetCustomAttributes在MethodBase對(duì)象上調(diào)用該函數(shù)。
獲取MethodBase對(duì)象的最簡(jiǎn)單方法是調(diào)用MethodBase.GetCurrentMethod。(請(qǐng)注意,您應(yīng)該添加[MethodImpl(MethodImplOptions.NoInlining)])
例如:
MethodBase method = MethodBase.GetCurrentMethod();
MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true)[0] ;
string value = attr.Value; //Assumes that MyAttribute has a property called Value
您也可以MethodBase手動(dòng)獲取,例如:(這樣會(huì)更快)
MethodBase method = typeof(MyClass).GetMethod("MyMethod");

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
可用的答案大多已過(guò)時(shí)。
這是當(dāng)前的最佳做法:
class MyClass
{
[MyAttribute("Hello World")]
public void MyMethod()
{
var method = typeof(MyClass).GetRuntimeMethod(nameof(MyClass.MyMethod), new Type[]{});
var attribute = method.GetCustomAttribute<MyAttribute>();
}
}
這不需要鑄造,使用起來(lái)非常安全。
您還可以.GetCustomAttributes<T>用來(lái)獲取一種類型的所有屬性。
- 2 回答
- 0 關(guān)注
- 554 瀏覽
添加回答
舉報(bào)