0

我试图返回两本词典并成功,但我对它不满意,因为它很慢。以下是我迄今为止对 Tupla 所做的:从另一个类中的一个方法返回两个带有 Tuple 的字典

这也是支持我关于 Tupla 很慢的声明的基准:http: //www.dotnetperls.com/multiple-return-values

考虑到从另一个类中的一个方法返回两个具有元组的字典的相同情况,我尝试使用 KeyValuePair 声明而不是 Tupla,但我收到此错误:

无法将类型“System.Tuple,System.Collections.Generic.Dictionary>”隐式转换为“System.Collections.Generic.KeyValuePair,System.Collections.Generic.Dictionary>”

这是代码:

class AClass
{
    Dictionary<string, string> dictOne = new Dictionary<string, string>();
    Dictionary<string, string> dictTwo = new Dictionary<string, string>();

    public KeyValuePair<Dictionary<string, string>, Dictionary<string, string>> MyMethodOne()
    {
        //Adding items dictOne and dictTwo

        return new KeyValuePair<Dictionary<string, string>, Dictionary<string, string>>(dictOne, dictTwo);
    }
}

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 get mentioned error
         KeyValuePair<Dictionary<string, string>, Dictionary<string, string>> calledKVP = _ac.MyMethodOne();

         Dictionary<string, string> dictThree = calledKVP.Key;
         Dictionary<string, string> dictFour = calledKVP.Value;
         //After this I loop through dictThree and dictFour and do what I need
        }
    }

恐怕这意味着它不能以“图普拉方式”的其他方式完成。

有什么建议么?

4

1 回答 1

4

首先你可以使用Tuple

public Tuple<Dictionary<T1, T2>, Dictionary<T1, T2>> GetDictionaries<T1, T2>()
{
    var dict1 = new Dictionary<T1, T2>();
    var dict2 = new Dictionary<T1, T2>();
    return Tuple.Create(dict1, dict2);
}

public void Method()
{
    var result = GetDictionaries(int, string);
    var dict1 = result.Item1;
    var dict2 = result.Item2;
}

具有多个输出参数的另一种解决方案是使用out参数

public void SetDictionaries(
    out Dictionary<int, string> dict1, out dictionary<int, double> dict2)
{

    dict1 = new Dictionary<int, string);
    dict2 = new Dictionary<int, double);

}

public void Method()
{
    Dictionary<int, string) dict1;
    Dictionary<int, double) dict2;

    SetDictionaries(out dict1, out dict2);
}

使用键值对

public KeyValuePair<Dictionary<int, int>, Dictionary<string, string>> GetDictionaries()
{
    var dict1 = new Dictionary<int, int>();
    var dict2 = new Dictionary<string, string>();

    return new KeyValuePair<Dictionary<int, int>, Dictionary<string, string>>(dict1, dict2);
}


public void Method()
{
    var result = GetDictionaries();
    var dict1 = result.Key;
    var dict2 = result.Value;
}
于 2012-12-05T09:16:18.897 回答