我有一个班级,班级 AClass 。在这个课程中我填写了两个词典,而且,我正在返回这两个词典,所以我使用了Tuple<Dictionary<string, string>, Dictionary<string, string>>
类型的方法声明:
class AClass
{
Dictionary<string, string> dictOne = new Dictionary<string, string>();
Dictionary<string, string> dictTwo = new Dictionary<string, string>();
public Tuple<Dictionary<string, string>, Dictionary<string, string>> MyMethodOne()
{
//Adding items dictOne and dictTwo
return new Tuple<Dictionary<string, string>, Dictionary<string, string>>(dictOne, dictTwo);
}
}
在其他班级 BClass 中,我应该获取这两个词典,访问它们并将它们的项目添加到另外两个词典中:
class BClass
{
AClass _ac = new AClass();
Dictionary<string, string> dictThree = new Dictionary<string, string>();
Dictionary<string, string> dictFour = new Dictionary<string, string>();
public void MyMethodTwo()
{
//Here I should get dictionaries through Tuple
//Add items from dictOne to dictThree
//Add items from dictTwo to dictFour
//In a way
// foreach (var v in accessedDict)
// {
// dictThree.Add(v.Key, v.Value);
// }
}
}
如果MyMethodOne
只返回一个字典,我会知道如何从一个字典到另一个字典,但在这里我有元组,我从未工作过,而且我不知道我知道如何获得这两个重调节值。我应该这样做吗?还有另一种方法,可能将方法声明为Dictionary< Dictionary<string, string>, Dictionary<string, string>>
?
那么,如何从Tuple获取字典?
答案 0 :(得分:2)
Tuple
类在名为“Item(Number)”的属性中公开其成员:http://msdn.microsoft.com/en-us/library/dd289533.aspx
因此,你的两项元组将具有名为Item1和Item2的属性:
var dictionaries = _ac.MyMethodOne();
// now dictionaries.Item1 = dictOne, dictionaries,Item2 = dictTwo
dictThree = dictionaries.Item1;
如果您只是想要获取对字典的引用或复制它,我不明白您何时要“分配项目”。如果要复制,请使用
dictFour = new Dictionary<string, string>(dictionaries.Item2);