对于初学程序员,是否有任何实用的元组示例?

时间:2010-08-13 22:33:03

标签: c# tuples

我正在为初级程序员制作C#4.0的教学视频。

对于我介绍的每个主题,我都包含一个学生可以实际使用的实际示例,例如,改进的COM Interop 功能,我展示了如何创建一个Excel文件并用代码中的值填充它。

对于命名和选项参数,我将展示如何使用5个参数创建日志记录方法,但如果您不想要,则不必传递任何参数,因为它们都具有默认值即可。所以他们看到这个功能如何更容易调用方法。

如果可以的话,我还想介绍元组,但似乎所有的“实际例子”(如此问题:Practical example where Tuple can be used in .Net 4.0?)都非常先进。使用该视频的学习者学习OOP,LINQ,使用泛型等,但是函数式编程或“解决Euler项目的问题11”超出了本视频的范围。

任何人都可以想到一个例子,其中元组实际上对初学程序员有用,或者某些例子,他们至少可以理解它们是如何被高级程序员使用的?他们的机制很直接 - 一个初学程序员要掌握的内容,我想找一个例子,以便学习者可以实际使用它们。有什么想法吗?

这是我到目前为止所拥有的,但它只是没有任何功能的干式机制:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //two ways to define them
            var customer = new Tuple<int, string, string>(23, "Sam", "Smith");
            var customer2 = Tuple.Create<int, string, string>(34, "James", "Allard");

            //with type inference, more concise (only available with the Create keyword)
            var customer3 = Tuple.Create(23, "John", "Hoopes");

            //you can go up to eight, then you have to send in another tuple
            var customer4 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10));

            Console.WriteLine(customer.Item1);
            Console.WriteLine(customer2.Item2);
            Console.WriteLine(customer3.Item3);
            Console.WriteLine(customer4.Rest.Item1.Item3);

            Console.ReadLine();
        }
    }
}

4 个答案:

答案 0 :(得分:13)

元组不一定是我为初学程序员解决的第一个主题......但是,有一些简单的例子。

我想到的是从执行搜索(或计算)的函数返回一个值(实际上可能为null),以及指示是否找到结果的布尔值。这是一种避免使用参数的方法,在某些情况下(例如LINQ查询)可能很麻烦或有问题:

public Tuple<string,bool> SearchDictionary( string searchKey )
{
    string value;
    bool wasFound = someDictionary.TryGetValue( searchKey, out value );
    return new Tuple<string,bool( value, wasFound );
}

// since <null> is a legal value to store in the dictionary, we cannot
// use it to distinguish between 'value not found' and 'value is null'.
// the Tuple<string,bool>, however, does allow us to do so...
var result = SearchDictionary( "somekey" );
if( result.Item2 )
{
    Console.WriteLine( result.Item1 );
}

我认为另一个自然的例子是在两个值之间创建关联而不为此目的创建一个显式类。例如,让我们想象一下我们想要代表将要打网球比赛的对手。我们可以使用:

// note the symmetry in the representation of opponents of a tennis match...
// if the relationship were asymmetrical, tuple may not be the best choice.
var playerA  = new TennisPlayer("Serena Williams");
var playerB  = new TennisPlayer("Venessa Williams");
var match    = new Tuple<TennisPlayer,TennisPlayer>( playerA, playerB );

使用元组代替,可以避免为这样的事情创建类。

最后一个例子是使用元组来表示字典中的复合键。由于Tuple<>可以相互比较以获得相等性,因此可以执行以下操作:

var complexDictionary = 
      new Dictionary<Tuple<string,int,decimal,DateTime>,string>();
complexDictionary.Add( new Tuple("USA",-4,1.671,DateTime.Now), "active" );
编辑:在教育开发人员使用元组时我会做的一个评论是元组应该很少(如果有的话)出现在你希望别人消费的代码的公共接口即可。作为简化类或模块内部实现的工具,我认为它们很好。但是一旦你开始将它们传入或传出方法,开发人员使用你的代码就必须与之交互,你就会遇到这样的问题,即元组模糊了API的语义。开发人员很难解释Tuple<int,int>应该是什么意思。在这种情况下,Item1Item2的含义是什么?当你发现自己需要在方法中传入或传出元组时,你应该强烈考虑编写一个类来封装和澄清这种关系。

答案 1 :(得分:5)

我能看到的最好的实际原因是将它们用作临时“类”。您希望关联多条信息,但不创建另一个类结构来保存它们。

它们应该是暂时的,因为如果你经常使用它们,你应该一路走下去并正确地创建类......

我想不出一个很好的具体例子,我主要将它们用于小事情,比如临时地图需要一个密钥,但价值中有多条信息......

答案 2 :(得分:2)

我用它们代替私人课程。在课堂上使用内部时非常棒。 将他们暴露在课堂之外只会导致混乱。我不得不打开课程以确定是什么。

答案 3 :(得分:0)

登录表格怎么样?他们一直在看那些。

var loginCredentials = 
    new Tuple<string, SecureString>(nameTextBox.Text, passwordTextBox.Text);

if (Login(loginCredentials))
    Console.Writeline("Login - Success!");
else
    Console.Writeline("Login - Failure");

...

public bool Login(Tuple<string, SecureString> loginCredentials)
{
    return ...
}