我需要能够从我的方法中读取属性的值,我如何才能做到这一点呢?

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

推荐答案

您需要对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");

.net相关问答推荐

ECS服务无法从Cognito获取配置

正则表达式匹配 URL 中的多个子目录

是否可以将 SandCastle 创建的两个页面合并到一个主页中?

使用 Thread.Abort() 有什么问题

为什么循环引用被认为是有害的?

抛出 ArgumentNullException

使用泛型装箱和拆箱

在 Moq Callback() 调用中设置变量值

.net:System.Web.Mail 与 System.Net.Mail

如何创建只读依赖属性?

获取类型的默认构造函数的最有效方法

实体框架 - 无法将 lambda 表达式转换为类型字符串,因为它不是委托类型

我应该在 LINQ 查询中使用两个where子句还是&&?

我可以在没有两个查询的情况下通过布尔标准将 IEnumerable 一分为二吗?

如何过滤具有多个条件的 Directory.EnumerateFiles?

找不到 System.Windows.Media 命名空间?

绑定在代码隐藏中定义的对象

如何判断枚举是否包含数字?

多个列表与 IEnumerable.Intersect() 的交集

我可以为 Dictionary 条目使用集合初始化程序吗?