代码之家  ›  专栏  ›  技术社区  ›  Michael Stum

在.NET中,tuple(T1)/singleton的用途是什么?

  •  32
  • Michael Stum  · 技术社区  · 16 年前

    .NET 4中的tuple类型之一是 Single-Element Tuple . 我只是想知道这个结构的目的是什么?

    我看到的唯一用途是在 8+ Tuple 因为它可以被分配到trest,在那里它实际上是有意义的。是这样吗?还是有其他目的?

    4 回复  |  直到 11 年前
        1
  •  18
  •   LBushkin    16 年前

    您必须要求BCL设计人员确定,但我怀疑,由于现实世界中存在一个1元组,.NET框架的作者希望在其实现中提供等效的对称性。

    Tuples 是.NET实现您认为 mathematical concept of a tuple .

    既然你在要求编程使用 Tuple<T> 我愿意 回答有.NET语言(如f)可以使用 Tuple<> 表示函数的返回值。因为f函数肯定会返回一个1元组,所以它为语言的行为和感觉增加了对称性和一致性。

    您的8+元组示例也可能是合法的,因为 Rest 属性可以是表示“溢出”的1元组。

        2
  •  7
  •   Ben McCormack    16 年前

    元组自动实现 IStructuralComparable IStructuralEquatable 以及其他事情。这样就可以直接对元组进行比较和排序。摘自比尔·麦卡锡2009年12月的文章

    Although tuples may look simple and nondescript, they do provide strong typing and important comparison and equality functionality. Tuples are useful across method, class or even machine boundaries.

    By putting your data type into a tuple, even of only one element, you are guaranteed immutability, equatability, and comparability. For tuples consisting of only one element, the main benefit of using a tuple is going to be immutability: once the tuple is created, it's data can never change for the life of the tuple.

        3
  •  4
  •   Oded    16 年前

    ITuple

        4
  •  3
  •   Community Mohan Dere    9 年前

    Why use a 1-tuple, Tuple<T1> in C#?

    可能的 usage of a 1-Tuple, is to return a null instance if there is no value, but that null of the item value itself, does not mean there is no result.

        static List<string> List = new List<string> {"a", "b", null, "c"};
    
        static Tuple<string> GetItemAtIndex(int index)
        {
            if (index < 0 || index >= List.Count)
                return null;
            return Tuple.Create(List[index]);
        }
    

    调用代码会知道当元组本身为空时,它不存在于列表中,但如果item1为空,则列表中实际上存在一个空项。当然,在本例中,存在许多更好的解决方法,但它也可以应用于数据库之外的结果:未找到结果或结果为空。

    Extending that same logic, a Tuple can be used to easily create generic methods that can return null for any type. 例如

        static Tuple<T> GetSomething<T, RecType>(RecType rec, Func<RecType, T> fn)
        {
            if (rec == null) return null;
            //extra example, access would be checked by something like CheckCurrentUserAccess(rec)
            bool AccesDenied = true;
            if (AccesDenied) return null; //sometimes you don't want to throw an exception ;)
    
            return Tuple.Create(fn(rec));
        }
    

    You could return Nullable<T> ,但这只适用于结构,在结构中,这适用于任何类型,尽管 int , string , int? , MyClass