Tuple 字面意思:元组。是.net4.0增加的新特性,是干什么的呢?总结一句,个人觉得这个东西 就是用来在有返回很多种类型的值时可以用到。它提供了8种类型的Tuple,直接看最复杂的那种(其实不是复杂,就是参数比别人多而已,原理是完全一致的),原理不讲太多,看下这个类的结构就知道什么原理了。
[Serializable, __DynamicallyInvokable]public class Tuple: IStructuralEquatable, IStructuralComparable, IComparable, ITuple{ // Fields private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; private readonly T6 m_Item6; private readonly T7 m_Item7; private readonly TRest m_Rest; // Methodspublic Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest); public override bool Equals(object obj); public override int GetHashCode(); int IStructuralComparable.CompareTo(object other, IComparer comparer); bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer); int IStructuralEquatable.GetHashCode(IEqualityComparer comparer); int IComparable.CompareTo(object obj); int ITuple.GetHashCode(IEqualityComparer comparer); string ITuple.ToString(StringBuilder sb); public override string ToString(); // Properties [__DynamicallyInvokable] public T1 Item1 { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; } 此处省略:T2到T6的定义,因为完全一致,为了减少文章篇幅。 [__DynamicallyInvokable] public T7 Item7 { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; } [__DynamicallyInvokable] public TRest Rest { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }//注意这个最后一个参数的类型,其实它是Tupple类型的 int ITuple.Size { get; }}
Tuple, IEnumerable , TRest> tuple=new Tuple(1,"string",true,'1',new Student(),.....,Tuple <任意类型> ); 用法就是在函数返回的时候,可以new一个这样的类型的对象,对其各个属性赋值,这样就可以返回非常多类型的数据,取得返回的值,就是用这个tuple对象.Item1,就可以获得相应类型的值,比如在这里我们tuple.Item1的值是1,tuple.Item2的值是“string”,以此类推。当然这些Item是只读的,不能对其进行赋值操作。为我们提供了很大的方便。以上是创建Tuple的方法之一,接下来说下另一个方法,先看下这个Tuple静态类: 任意类型>
[__DynamicallyInvokable]public static class Tuple{ // Methods internal static int CombineHashCodes(int h1, int h2);internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8); [__DynamicallyInvokable] public static TupleCreate (T1 item1);
此处省略:T2到T6的定义,因为完全一致,为了减少文章篇幅。
[__DynamicallyInvokable] public static Tuple> Create (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8); }
其实代码更多,当然区别也是参数个数不一致,原理还是一样的,这里只写出两个。
看一眼就知道Create<....>这个方法,没错我们也可以通过Tuple这个静态类中的Create静态方法来创建不定个数参数的Tuple对象,举个例子:
var trest = Tuple.Create (8);var t8 = Tuple.Create