2 回答

TA貢獻1862條經(jīng)驗 獲得超6個贊
您需要GetCustomAttributes在MethodBase對象上調用該函數(shù)。
獲取MethodBase對象的最簡單方法是調用MethodBase.GetCurrentMethod。(請注意,您應該添加[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手動獲取,例如:(這樣會更快)
MethodBase method = typeof(MyClass).GetMethod("MyMethod");

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