第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

讀取方法屬性的值

讀取方法屬性的值

三國紛爭 2019-12-03 09:58:15
我需要能夠從我的方法中讀取屬性的值,該怎么辦?[MyAttribute("Hello World")]public void MyMethod(){    // Need to read the MyAttribute attribute and get its value}
查看完整描述

2 回答

?
阿波羅的戰(zhàn)車

TA貢獻1862條經(jīng)驗 獲得超6個贊

您需要GetCustomAttributes在MethodBase對象上調用該函數(shù)。

獲取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條經(jīng)驗 獲得超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 關注
  • 546 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號