我有一個包含4個字典的類。C#中的字符串獲取字典名稱#
public class FishInformation
{
public int FishId { get; set; }
public Dictionary<string,int> DicGroup { get; set; }
public Dictionary<string, int> DicEvent { get; set; }
public Dictionary<string, int> DicAudience { get; set; }
public Dictionary<string, int> DicType { get; set; }
}
我想通過字符串獲取字典名稱並向其中添加項目。所以this question建議使用System.Reflection
這樣做。這是我試過的代碼:
FishInformation fishinfo =new Global.FishInformation
{
FishId = fishId,
DicAudience = new Dictionary<string, int>(),
DicEvent = new Dictionary<string, int>(),
DicGroup = new Dictionary<string, int>(),
DicType = new Dictionary<string, int>()
};
string relatedDictionary //It's the variable which contains the string to merge with "Dic" to get the property
fishinfo.GetType().GetProperty("Dic" + relatedDictionary).SetValue(fishinfo, myKey, myValue);
我只是想弄清楚如何使它工作!
我必須在'Dictionaries = new ...'之前加'var'嗎? Cz它拋出錯誤沒有它 – 2014-12-07 09:16:45
反正,就像這個想法!謝謝 – 2014-12-07 09:32:33
不,你不可以在字典之前放var,因爲它是一個屬性,你給它賦了一個新的值。如果你把var放在那裏,它會使它變成局部變量,並且不再工作。如果你得到一個錯誤,那麼你需要定義屬性。我想你可能會監督它? – t3chb0t 2014-12-07 12:12:18