我需要能够从我的方法中读取属性的值,该怎么做?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}
Answers:
您需要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();
}
可用的答案大多已过时。
这是当前的最佳做法:
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>
用来获取一种类型的所有属性。
nameof
是非常好的。
如果将默认属性值存储到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;
}
}
如果您要实现上述@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.
}
}