字符串获取字典名称

字符串获取字典名称

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


我只能弄清楚如何使其工作!

最佳答案

为什么这么复杂?我建议这种解决方案/设计:

class Program
{
    static void Main(string[] args)
    {
        string dicName = "Group";
        var fishInfo = new FishInformation();
        string myKey = "myKey";
        int myValue = 1;
        fishInfo.Dictionaries[dicName][myKey] = myValue;
    }
}

public class FishInformation
{
    public FishInformation()
    {
        Dictionaries = new Dictionary<string, Dictionary<string, int>>()
        {
            { "Group", new Dictionary<string, int>() },
            { "Event", new Dictionary<string, int>() },
            { "Audience", new Dictionary<string, int>() },
            { "Type", new Dictionary<string, int>() }
        };
    }

    public int FishId { get; set; }

    public Dictionary<string, Dictionary<string, int>> Dictionaries { get; set; }

    public Dictionary<string, int> GroupDic
    {
        get { return Dictionaries["Group"]; }
    }

    // ... other dictionary getters ...
}

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

10-09 03:57