Tuples in .Net 4 (System.Tuple)

 

.Net 4 brings with it the Tuple type! I have never worked with tuples in programming before and have a hard time seeing their purpose but here is an example of a tuple in C#:

 

什么是Tuple,在汉语上我们将其翻译为元组。Tuple的概念源于数学概念,表示有序的数据集合。在.NET中Tuple被实现为泛型类型,n-Tuple表示有n个元素的Tuple,集合的元素可以是任何类型

 

var tupleOne = new Tuple<int, string>(1, "Hello World");
Console.WriteLine("Tuple contains: " + tupleOne.Item1 + " and " + tupleOne.Item2);

There are also some factory methods for creating tuples:

var tupleTwo = Tuple.Create("Hello World", 2010);
var tupleThree = Tuple.Create("Hello World", 2010, new SomeClass());
Console.WriteLine("Tuple contains: " + tupleThree.Item1 + ", " + tupleThree.Item2 + " and " + tupleThree.Item3.MyProperty);

Tuple facts:

  • Tuples are immutable
  • Tuples are reference types
  • Located in System.Tuple
  • Can take up to 8 generic parameters, but can contain an infinite number of elements.
  • Elements are always named Item1, Item2… Item7, Rest

See msdn for more information.

为什么要用Tuple呢?这是个值得权衡的问题,上述MyRequest类型中通过3-Tuple对需要的Request信息进行封装,我们当然也可创建一个新的struct来封装,两种方式均可胜任。然则,在实际的编程实践中,很多时候我们需要一种灵活的创建一定数据结构的类型,很多时候新的数据结构充当着“临时”角色,通过大动干戈新类型完全没有必要,而Tuple既是为此种体验而设计的。例如:

  • Point {X, Y},可以表示坐标位置的数据结构。
  • Date {Year, Month, Day},可以表示日期结构;Time {Hour, Minute, Second},可以表示时间结构;而DateTime {Date, Time}则可以实现灵活的日期时间结构。
  • Request {Name, URL, Result},可以表示Request的若干信息。
  • 。。。,随需而取。

http://technet.microsoft.com/zh-cn/library/dd387150(v=VS.95)

你可能感兴趣的:(System)