使用元组Tuple,返回多个不同类型的值

时间:2021-02-28 00:48:15

  记得我在不知道Tuple时,如果想实现调用某个函数时,返回多个值,则需要使用ref或者out了。

     string name = "";
int result= GetInfo(ref name);     public int GetInfo(ref string name)
{
name = "testName";
return ;
}

   调用GetInfo()函数后,返回name=testName,result=2。

   C# 4.0后有了元组Tuple,可以将不同类型的数据都丢进去,并且一次性返回,但数量是有限的,里面最多只能放8个吧。

  看看下面的代码示例:

   var tupleTest = GetMoreInfo();

    var t1 = tupleTest.Item1;
var t2 = tupleTest.Item2;
  public Tuple<IEnumerable<string>, Dictionary<string, string>> GetMoreInfo()
{
List<string> cityList = new List<string>();
cityList.Add("Beijing");
cityList.Add("GuangZhou"); Dictionary<string, string> zipCodeDictonary = new Dictionary<string, string>();
zipCodeDictonary.Add("Beijing", "");
zipCodeDictonary.Add("GuangZhou", ""); return Tuple.Create<IEnumerable<string>, Dictionary<string, string>>(cityList, zipCodeDictonary);
}