读取方法属性的值

Cop*_*ill 60 .net c# reflection methods attributes

我需要能够从我的方法中读取我的属性的值,我该怎么做?

[MyAttribute("Hello World")]
public void MyMethod()
{
    // Need to read the MyAttribute attribute and get its value
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 77

您需要GetCustomAttributesMethodBase对象上调用该函数.
获取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
Run Code Online (Sandbox Code Playgroud)

您也可以MethodBase手动获取,如下所示:(这会更快)

MethodBase method = typeof(MyClass).GetMethod("MyMethod");
Run Code Online (Sandbox Code Playgroud)


Nag*_*agg 31

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


Maf*_*fii 16

可用的答案大多已过时.

这是目前的最佳做法:

class MyClass
{

  [MyAttribute("Hello World")]
  public void MyMethod()
  {
    var method = typeof(MyClass).GetRuntimeMethod(nameof(MyClass.MyMethod), new Type[]{});
    var attribute = method.GetCustomAttribute<MyAttribute>();
  }
}
Run Code Online (Sandbox Code Playgroud)

这不需要铸造,使用起来非常安全.

您还可以使用.GetCustomAttributes<T>获取一种类型的所有属性.

  • `nameof` 非常好。 (2认同)