Я должен смочь считать значение своего атрибута из моего Метода, как я могу сделать это?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}
Вам необходимо вызвать функцию GetCustomAttributes
для объекта MethodBase
.
Самый простой способ получить объект 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");
[MyAttribute("Hello World")]
public int MyMethod()
{
var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault();
}