我需要能够从我的方法中读取属性的值,我该怎么做呢?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}发布于 2016-09-30 22:07:27
可用的答案大多是过时的。
这是当前的最佳实践:
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>来获取一种类型的所有属性。
https://stackoverflow.com/questions/2493143
复制相似问题