在C#中按字符串获取字典名称

时间:2014-12-07 07:48:33

标签: c# dictionary reflection

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

我只是想弄清楚如何让它发挥作用!

3 个答案:

答案 0 :(得分:2)

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

您需要致电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];
    }
}

答案 1 :(得分:1)

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

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 ...
}

答案 2 :(得分:0)

如果我理解你的问题,你可能需要首先调用GetValue()来检索字典,将项目添加到字典中,最后调用SetValue()(刮开);因为你试图修改字典内容而不是整个字典。

编辑:当您处理参考类型时,SetValue()是不必要的。