0

我有一堂课,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只返回一本字典,我会知道如何从一本字典中获取项目到另一本字典,但在这里我有Tuple,我从未使用过它,而且我不知道如何获得这两个重新调整的值。我应该这样做吗?还有另一种方法,也许将方法声明为Dictionary< Dictionary<string, string>, Dictionary<string, string>>

那么,如何从 Tuple 中获取字典呢?

4

1 回答 1

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);
于 2012-12-04T15:14:26.153 回答