我需要能够从我的方法中读取属性的值,我如何才能做到这一点呢?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}
我需要能够从我的方法中读取属性的值,我如何才能做到这一点呢?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}
您需要对MethodBase
对象调用GetCustomAttributes
函数.
获取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");