读取方法属性的值


70

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

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

这些方法也有通用版本(您不需要强制转换!),它们是在.net的较新版本(我认为4.0之后)中作为扩展实现的,因此,访客请查看除公认的答案以外的其他答案
-Mafii

Answers:


84

您需要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

您也可以MethodBase手动获取,例如:(这样会更快)

MethodBase method = typeof(MyClass).GetMethod("MyMethod");

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

几年后,凌晨3点左右,上面的评论绝对让我流下了笑声……很棒。@Oded
Wingfield

Hahahahah @Oded那是一位出色的伴侣
Mavi Domates

21

可用的答案大多已过时。

这是当前的最佳做法:

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>用来获取一种类型的所有属性。


1
nameof是非常好的。
Shaun Luttin '16

0

如果将默认属性值存储到Name构造中的属性(在我的示例中),则可以使用静态Attribute helper方法:

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;
    }
}

0

如果您要实现上述@Mikael Engver之类的设置,并允许多次使用。您可以执行以下操作来获取所有属性值的列表。

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class TestCase : Attribute
{
    public TestCase(string value)
    {
        Id = value;
    }

    public string Id { get; }        
}   

public static IEnumerable<string> AutomatedTests()
{
    var assembly = typeof(Reports).GetTypeInfo().Assembly;

    var methodInfos = assembly.GetTypes().SelectMany(m => m.GetMethods())
        .Where(x => x.GetCustomAttributes(typeof(TestCase), false).Length > 0);

    foreach (var methodInfo in methodInfos)
    {
        var ids = methodInfo.GetCustomAttributes<TestCase>().Select(x => x.Id);
        yield return $"{string.Join(", ", ids)} - {methodInfo.Name}"; // handle cases when one test is mapped to multiple test cases.
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.