我有一个包含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