返回多个值的方法
在开发过程中,经常遇到方法需要返回多个值的情况。方法可以传入多个参数,但一般只能返回一个值,通常的解决方案如下:
- 自定义一个 class 或 struct ,将多个返回值打包一个对象实例或结构体变量返回;
- 在方法内部改变方法所在类的字段或属性,处理返回值时直接读取类的字段或属性;
- 使用带out或ref关键字的变量接受返回值;
通常返回的多个值并不具有强烈的联系,它们一般由一个作为结果的主要返回值和其它描述计算状态的返回值组成,使用class 或 struct会导致代码变得结构混乱,而且这些class 或 struct一般只使用一次。
通过类的字段或属性返回多个值,会导致线程安全的问题,且静态方法只能改写静态变量。
使用带out或ref关键字的变量接受返回值是最常见的用法,但使用out关键字时必须在外部先申明一个变量,且返回值太多时会导致方法需要传入大量的参数。
这里介绍如何使用 .NET Framework 4.0 的 Tuple 来实现方法返回多个返回值。
Tuple使用实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double a = 8;
double b = 0;
var c = DoubleDivision(a, b);
if (c.Item1)
{
Console.WriteLine("{0}除于{1}等于{2}",a,b,c.Item2);
}
else Console.WriteLine("除数等于0,不能相除,结果为{0}",c.Item2);
Console.ReadLine();
}
private static Tuple<bool, double> DoubleDivision(double dividend, double divisor)
{
if (divisor != 0)
{
return Tuple.Create(true, dividend / divisor);
}
else
{
return Tuple.Create(false, (double)0);
}
}
}
}
Tuple通常可以包含7个组件,当要包含8个或更多的组件时可使用Tuple<T1,T2,T3,T4,T5,T6,T7,TRest>
var from1980 = Tuple.Create(1203339, 1027974, 951270);
var from1910 = new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>>
(465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980);
var population = new Tuple<string, int, int, int, int, int, int,
Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>>>
("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910);
使用建议
Tuple 的 Item 不要过多,方法的注释中要说明各个 Item 代表的含义;
Tuple用完就可以丢弃,不要多次重复使用。