Подтвердить что ты не робот

Прочитать значение атрибута метода

Мне нужно уметь читать значение моего атрибута из моего метода, как я могу это сделать?

[MyAttribute("Hello World")]
public void MyMethod()
{
    // Need to read the MyAttribute attribute and get its value
}
4b9b3361

Ответ 1

Вам нужно вызвать функцию 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");

Ответ 2

[MyAttribute("Hello World")]
public int MyMethod()
{
var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault();
}

Ответ 3

Доступные ответы в основном устарели.

Это лучшая практика:

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> для получения всех атрибутов одного типа.

Ответ 4

Если вы сохраняете значение атрибута по умолчанию в качестве свойства (Name в моем примере) при построении, вы можете использовать статический атрибут атрибута:

using System;
using System.Linq;

public class Helper
{
    public static TValue GetMethodAttributeValue<TAttribute, TValue>(Action action, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute
    {
        var methodInfo = action.Method;
        var attr = methodInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        return attr != null ? valueSelector(attr) : default(TValue);
    }
}

Использование:

var name = Helper.GetMethodAttributeValue<MyAttribute, string>(MyMethod, x => x.Name);

Мое решение основано на том, что значение по умолчанию задано для построения атрибута, например:

internal class MyAttribute : Attribute
{
    public string Name { get; set; }

    public MyAttribute(string name)
    {
        Name = name;
    }
}