为了账号安全,请及时绑定邮箱和手机立即绑定

读取方法属性的值

读取方法属性的值

三国纷争 2019-12-03 09:58:15
我需要能够从我的方法中读取属性的值,该怎么办?[MyAttribute("Hello World")]public void MyMethod(){    // Need to read the MyAttribute attribute and get its value}
查看完整描述

2 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

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


查看完整回答
反对 回复 2019-12-03
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

可用的答案大多已过时。


这是当前的最佳做法:


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


查看完整回答
反对 回复 2019-12-03
  • 2 回答
  • 0 关注
  • 469 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信