我正在为初级程序员制作 C# 4.0 的教学视频。
对于我介绍的每个主题,我都包含一个学生可以实际使用的实际示例,例如,对于改进的 COM Interop 功能,我展示了如何创建一个 Excel 文件并用代码中的值填充它。
对于命名参数和选项参数,我展示了如何使用 5 个参数创建一个日志记录方法,但如果您不需要,则不必传递任何参数,因为它们都有默认值强>。因此,他们看到使用此功能如何更轻松地调用方法。
如果可以的话,我也想介绍元组,但似乎所有的“实际例子”(如本题:Practical example where Tuple can be used in .Net 4.0?)都非常高级。使用视频的学习者学习 OOP、LINQ、使用泛型等,但例如函数式编程或“解决欧拉计划第 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();
}
}
}
最佳答案
元组不一定是我要为初学者解决的第一个主题......但是,有一些简单的例子。
我想到的是从执行搜索(或计算)的函数返回一个值(实际上可能为空),以及一个指示是否找到结果的 bool 值。这是一种避免使用 out 参数的方法,这在某些情况下(如 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<>
s 可以相互比较以获得相等性,因此可以执行以下操作:
var complexDictionary =
new Dictionary<Tuple<string,int,decimal,DateTime>,string>();
complexDictionary.Add( new Tuple("USA",-4,1.671,DateTime.Now), "active" );
编辑:在向开发人员介绍元组的使用时,我会发表的一个评论是,元组应该很少(如果有的话)出现在您希望其他人使用的代码的公共(public)接口(interface)中强>。作为简化类或模块内部实现的工具,我认为它们很好。但是一旦您开始将它们传入或传出使用您的代码的开发人员必须与之交互的方法,您就会遇到元组模糊 API 语义的问题。开发人员很难解释什么 Tuple<int,int>
应该是什么意思做什么Item1
或 Item2
在这种情况下是什么意思?当您看到自己需要将元组传入或传出方法时,您应该强烈考虑编写一个类来封装和阐明这种关系。
关于c# - 是否有适合初学者的元组的实际示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3481113/