我需要能够从我的方法中读取属性的值,该怎么办?
[MyAttribute("Hello World")] public void MyMethod() { // Need to read the MyAttribute attribute and get its value }
您需要GetCustomAttributes在MethodBase对象上调用该函数。 获取MethodBase对象的最简单方法是调用MethodBase.GetCurrentMethod。(请注意,您应该添加[MethodImpl(MethodImplOptions.NoInlining)])
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");