gpt4 book ai didi

c# - 在C#中通过字符串获取字典名称

转载 作者:太空宇宙 更新时间:2023-11-03 23:46:53 24 4
gpt4 key购买 nike

我有一个包含 4 个词典的类。

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);

我只是想知道如何让它发挥作用!

最佳答案

您的代码设置整个字典的值,而不是将字符串添加到现有字典。

您需要调用GetValue , 不是 SetValue , 转换到 IDictionary<string,int> ,并为其添加值:

var dict = (IDictionary<string,int>)fishinfo
.GetType()
.GetProperty("Dic" + relatedDictionary)
.GetValue(fishinfo);
dict[myKey] = myValue;

这不是执行此操作的最有效方法 - 您可以使用 enum相反:

enum InfoDict {Group, Event, Audience, Type};
public class FishInformation {
public int FishId { get; set; }
private IDictionary<string,int>[] infos = new IDictionary<string,int>[] {
new Dictionary<string,int>()
, new Dictionary<string,int>()
, new Dictionary<string,int>()
, new Dictionary<string,int>()
};
public IDictionary<string,int> GetDictionary(InfoDict index) {
return infos[index];
}
}

关于c# - 在C#中通过字符串获取字典名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27340759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com