C#调用字典<;字符串,字符串>;基于从另一个字典返回的值

C#调用字典<;字符串,字符串>;基于从另一个字典返回的值,c#,dictionary,reflection,C#,Dictionary,Reflection,是否有一种基于返回值动态调用相关词典的方法 因此,在下面的示例中,从TestDictionary返回的值shouldBeDictionary1将根据传递的键G从Dictionary1返回绿色值: private static readonly Dictionary<string, List<string>> TestDictionary = new Dictionary<string, List<string>> { { "Bla

是否有一种基于返回值动态调用相关词典的方法

因此,在下面的示例中,从TestDictionary返回的值shouldBeDictionary1将根据传递的键G从Dictionary1返回绿色值:

private static readonly Dictionary<string, List<string>> TestDictionary = new Dictionary<string, List<string>>
{
    { "Blah", new List<string>(new[] { "Something", "Dictionary1" })},
    { "Blah, blah", new List<string>(new[] { "Something else", "Dictionary2" }) }        
};

private static readonly Dictionary<string, string> Dictionary1 = new Dictionary<string, string>
{
    { "G", "Green"},
    { "A", "Amber"},
    { "R", "Red"}
};

private static readonly Dictionary<string, string> Dictionary2 = new Dictionary<string, string>
{
    { "B", "Blue"},
    { "P", "Purple"}
};

private string Test()
{
    var shouldBeSomething = TestDictionary["Blah"][0];

    var shouldBeDictionary1 = TestDictionary["Blah"][1];

    return shouldBeDictionary1["G"] // returned value should be Green

    //MethodInfo methodInfo = typeof(Dictionary<string, string>).GetMethod(shouldBeDictionary1)
}
private static readonly Dictionary TestDictionary=新字典
{
{“废话”,新列表(新[]{“某物”,“词典1”}),
{“废话,废话”,新列表(新[]{“其他东西”,“字典2”})
};
私有静态只读字典Dictionary 1=新字典
{
{“G”,“绿色”},
{“A”,“琥珀”},
{“R”,“红色”}
};
私有静态只读字典Dictionary 2=新字典
{
{“B”,“蓝色”},
{“P”,“紫色”}
};
私有字符串测试()
{
var shouldBeSomething=TestDictionary[“Blah”][0];
var应该是dictionary=TestDictionary[“Blah”][1];
return shouldbedictional1[“G”]//返回值应为绿色
//MethodInfo MethodInfo=typeof(字典).GetMethod(应为字典1)
}
在上面的示例中,试图使用反射,methodInfo返回null,因此无法使用Invoke


如果您有任何建议,我们将不胜感激。

当然有,请将您对词典的引用存储在它自己的词典中:

var dictionaryIndex = new Dictionary<string,Dictionary<string,string>>{
  ["Dictionary1"] = new Dictionary<string, string>
  {
    { "G", "Green"},
    { "A", "Amber"},
    { "R", "Red"}
  },
  ["Dictionary2"] = new Dictionary<string, string>
  {
    { "B", "Blue"},
    { "P", "Purple"}
  }
};

var shouldBeSomething = TestDictionary["Blah"][0];

var shouldBeDictionary1 = TestDictionary["Blah"][1];

return dictionaryIndex[shouldBeDictionary1]["G"] // returned value should be Green
var dictionaryIndex=新字典{
[“Dictionary1”]=新字典
{
{“G”,“绿色”},
{“A”,“琥珀”},
{“R”,“红色”}
},
[“Dictionary2”]=新字典
{
{“B”,“蓝色”},
{“P”,“紫色”}
}
};
var shouldBeSomething=TestDictionary[“Blah”][0];
var应该是dictionary=TestDictionary[“Blah”][1];
return dictionaryIndex[shouldbedictionar1][“G”]//返回值应为绿色

为什么您要按名称引用其他词典而不是引用?谢谢您,但是我上面的示例非常简单,实际问题可能涉及100多个翻译词典,跨越多种方法。您的解决方案将为每个方法调用100个字典。@iggyweb好的,我只能根据您问题中的信息回答……顺便说一句,您不必重复,您的
字典索引可以是静态的谢谢@Jamiec,正如您正确指出的那样,创建一个
私有静态只读字典DictionaryIndex=newdictionary
做得很好,谢谢。