亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

有沒有一種方法可以訪問類的成員,在訪問時使用字符串而不是類名

有沒有一種方法可以訪問類的成員,在訪問時使用字符串而不是類名

C#
繁花不似錦 2023-07-09 16:21:02
我希望使用一些反射來訪問類中的所有成員并獲取它們的值。這是班級的。我總是初始化“Championsids”類。(我知道有很多代碼,但它非常簡單)。當我初始化它時,值會自動分配給所有成員。一切正常ChampionIds championIds = JsonConvert.DeserializeObject<ChampionIds>(json2); //Assignment works perfect!現在我可以這樣訪問所有值。僅作為使用示例Console.WriteLine(championIds.data.Aatrox.id);Console.WriteLine(championIds.data.Aatrox.key);Console.WriteLine(championIds.data.AurelionSol.version);Console.WriteLine(championIds.data.AurelionSol.title);但問題是我想將所有不同的冠軍鍵和名稱放入字典中。所以像這樣的事情。Dictionary<string, string> ChampIdDict = new Dictionary<string, string>();ChampIdDict.Add(championIds.data.Aatrox.key, championIds.data.Aatrox.name);我想為每個冠軍做到這一點。對于這樣的例子Dictionary<string, string> ChampIdDict = new Dictionary<string, string>();ChampIdDict.Add(championIds.data.Aatrox.key, championIds.data.Aatrox.name);ChampIdDict.Add(championIds.data.Ahri.key, championIds.data.Ahri.name);ChampIdDict.Add(championIds.data.Akali.key, championIds.data.Akali.name);//and so on但我不想以這種方式在我的代碼中編寫 100 行。所以我遍歷所有成員并使用此代碼輕松獲取他們的名字FieldInfo[] fields = typeof(Data).GetFields();foreach (var field in fields){     Console.WriteLine(field.Name);}結果是這樣的AatroxAhriAkaliAlistarAmumuAnivia//and so on我該怎么做才能做到這一點FieldInfo[] fields = typeof(Data).GetFields();foreach (var field in fields){    Console.WriteLine("Inserting champion = " + field.Name + " into the dictionary");    string key = championIds.data.(field.Name).key;    string name = championIds.data.(field.Name).name;    ChampIdDict.Add(key, name)}結果是我簡單地從網站獲取冠軍 id,然后我說 string returnedChampionId = //from website ex. 第266章 266謝謝閱讀。希望你能推薦一些東西
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

您需要從每個字段獲取值并將其轉換為適當的類型。然后就可以訪問內部屬性了


Data actualDataObject = // whereever you get it from

Dictionary<string, string> ChampIdDict = new Dictionary<string, string>();


FieldInfo[] fields = typeof(Data).GetFields();

foreach (var field in fields)

{

    Champions temp = (Champions)field.GetValue(actualDataObject);

    string key = temp.key;

    string name = temp.name;

    ChampIdDict.Add(key, name)

}

在 linq 中,這可能看起來像這樣:


Dictionary<string, string> ChampIdDict = (from field in fields

                                    let temp = (Champions)field.GetValue(actualDataObject)

                                    select new {key = temp.key, name = temp.name})

                                   .ToDictionary(x => x.key, x => x.name);


查看完整回答
反對 回復 2023-07-09
  • 1 回答
  • 0 關注
  • 139 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號