现在的位置: 首页 > 综合 > 正文

关于.net 4.0新增的 Tuple类

2012年11月12日 ⁄ 综合 ⁄ 共 640字 ⁄ 字号 评论关闭

引:

在很多场合的,我们需要一个方法返回多个值,我们有多种方式来实现。

1.使用全局变量

2.使用out 和 ref 参数

3.把多个返回值封装为  struct 或 class

4.使用Tuple

 

.net 4.0在基类库中添加了一个有趣的 Tuple类,它代表一个有序的N元组。所谓元组,其实就是“数值对”,比如以下就是一个3元组:(100,200,300)

可以调用Tuple.Create静态方法或使用new 关键字直接创建一个Tuple对象。  .net 类库中定义了拥有1-7个泛型参数的泛型Tuple.

使用Tuple对象作为方法返回值,可以很容易地包含多个结果。

namespace DivideUseTuple
{
class Program
{
static void Main(string[] args)
{

Tuple<int, int> result = Divide(10, 3);
Console.WriteLine("{0} {1}", result.Item1, result.Item2); // 输出 "3 1"
}
static Tuple<int, int> Divide(int x, int y)
{
return new Tuple<int, int>(x / y, x % y);
}

}
}

Tuple实现了 IStructuralEquatable , IStructuralComparable 和 IComparable接口,这意味着Tuple变量可以直接对比内容。

 

上面只是做为引,引出Tuple,事实上Tuple可以有更多的用途。

待日后用到再作补充。。。。

抱歉!评论已关闭.