我需要能够从我的方法中读取属性的值,我该怎么做呢?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}发布于 2010-03-22 22:56:50
您需要在MethodBase对象上调用GetCustomAttributes函数。
获取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");发布于 2010-03-22 22:56:11
[MyAttribute("Hello World")]
public int MyMethod()
{
var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault();
}发布于 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
复制相似问题