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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

讀取方法屬性的值

讀取方法屬性的值

三國(guó)紛爭(zhēng) 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貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊

您需要GetCustomAttributes在MethodBase對(duì)象上調(diào)用該函數(shù)。

獲取MethodBase對(duì)象的最簡(jiǎn)單方法是調(diào)用MethodBase.GetCurrentMethod。(請(qǐng)注意,您應(yīng)該添加[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手動(dòng)獲取,例如:(這樣會(huì)更快)


MethodBase method = typeof(MyClass).GetMethod("MyMethod");


查看完整回答
反對(duì) 回復(fù) 2019-12-03
?
Smart貓小萌

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊

可用的答案大多已過(guò)時(shí)。


這是當(dāng)前的最佳做法:


class MyClass

{


  [MyAttribute("Hello World")]

  public void MyMethod()

  {

    var method = typeof(MyClass).GetRuntimeMethod(nameof(MyClass.MyMethod), new Type[]{});

    var attribute = method.GetCustomAttribute<MyAttribute>();

  }

}

這不需要鑄造,使用起來(lái)非常安全。


您還可以.GetCustomAttributes<T>用來(lái)獲取一種類型的所有屬性。


查看完整回答
反對(duì) 回復(fù) 2019-12-03
  • 2 回答
  • 0 關(guān)注
  • 554 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)