对于初学者来说,有没有元组的实用示例?

发布于 2024-09-14 23:05:56 字数 1701 浏览 3 评论 0原文

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

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

对于命名参数和选项参数,我展示了如何创建具有 5 个参数的日志记录方法,但如果您不需要,则不必传递任何参数,因为它们都有默认值。因此他们看到使用此功能如何更轻松地调用方法。

如果可以的话,我还想介绍元组,但似乎所有“实际示例”(如这个问题中:Tuple 可以在 .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();
        }
    }
}

I am making an instructional video for C# 4.0 for beginning programmers.

For every topic I introduce I include a practical example which the student could actually use, for instance, for the improved COM Interop functionality, I show how to create an Excel file and fill it with values from code.

For named and option parameters I show how you can create a logging method with 5 parameters but don't have to pass any if you don't want since they all have default values. So they see how calling methods is easier with this feature.

I would also like to introduce tuples as well if I can, but it seems that all the "practical examples" (as in this question: Practical example where Tuple can be used in .Net 4.0?) are very advanced. The learners that use the video learn OOP, LINQ, using generics, etc. but e.g. functional programming or "solving Problem 11 of Project Euler" are beyond the scope of this video.

Can anyone think of an example where tuples would actually be useful to a beginning programmer or some example where they could at least understand how they could be used by and advanced programmer? Their mechanics are quite straight-forward for a beginning programmer to grasp, I would just like to find an example so that the learner could actually use them for a practical reason. Any ideas?

Here's what I have so far, but it is just dry mechanics without any functionality:

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();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梨涡少年 2024-09-21 23:05:56

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

我想到的是从执行搜索(或计算)的函数返回一个值(实际上可能为空),以及一个指示是否找到结果的布尔值。这是一种避免使用 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<> 可以相互比较以确保相等,因此可以执行以下操作:

var complexDictionary = 
      new Dictionary<Tuple<string,int,decimal,DateTime>,string>();
complexDictionary.Add( new Tuple("USA",-4,1.671,DateTime.Now), "active" );

编辑:在向开发人员介绍元组的使用时我会发表的一个评论是 元组应该很少(如果有的话)出现在您希望其他人使用的代码的公共接口。作为简化类或模块内部实现的工具,我认为它们很好。但是,一旦您开始将它们传入或传出使用代码的开发人员必须与之交互的方法,您就会遇到元组模糊 API 语义的问题。开发人员很难解释 Tuple 的含义。在这种情况下,Item1Item2 意味着什么?当您发现自己需要将元组传入或传出方法时,您应该强烈考虑编写一个类来封装和阐明这种关系。

Tuples are not necessarily the first topic I would tackle for beginner programmers ... however, there are some simple examples.

One that comes to mind is returning a value (which may actually be null) from a function that performs a search (or calculation), together with a boolean that indicates whether the result was found or not. It's an approach that avoids using out parameters, which can be cumbersome or problematic in certain scenarios (like LINQ queries):

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 );
}

Another example that I think is natural, is creating associations between two values without creating an explicit class for the purpose. For example, let's imagine we want to represent pairs of opponents who will play tennis matches. We could use:

// 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 );

Creating a class for something like this can be avoided by using tuples instead.

A final example, is using tuples to represent composite keys in a dictionary. Since Tuple<>s can be compared to one another for equality, it becomes possible to do stuff like:

var complexDictionary = 
      new Dictionary<Tuple<string,int,decimal,DateTime>,string>();
complexDictionary.Add( new Tuple("USA",-4,1.671,DateTime.Now), "active" );

EDIT: One comment I would make when educating developers about the use of tuples, is that tuples should rarely (if ever) appear in the public interface of code you expect others to consume. As tools to simplify the internal implementation of a class or module, I think they're fine. But once you start passing them in or out of methods that developers consuming your code have to interact with, you run in the problem that tuples obscure the semantics of your API. It becomes hard for developers to interpret what Tuple<int,int> is supposed to mean. What do Item1 or Item2 mean in such a case? When you see yourself needing to pass tuples in or out of methods, you should strongly consider writing a class to encapsulate and clarify the relationship.

将军与妓 2024-09-21 23:05:56

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

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

我想不出一个好的具体示例,我已经主要将它们用于小事情,例如需要单个键但值中需要多条信息的临时地图......

The best practical reason i can see is using them as temporary "classes". You want to associate multiple pieces of information, but not create yet another class structure to hold them.

They should be temporary, because if you're using them a lot, you should be going all the way and properly creating classes...

I can't think of a good specific example, i've mostly used them for small things, like temporary maps that need a single key but multiple pieces of information in the value...

就像说晚安 2024-09-21 23:05:56

我用它们代替私人课程。在类中内部使用时非常有用。
将它们暴露在课堂之外只会导致混乱。我一直不得不开课来确定什么是什么。

I use them in place of private classes. The are great when used internally in a class.
Exposing them outside the class only led to confusion. I kept having to open the class to determine what was what.

挖个坑埋了你 2024-09-21 23:05:56

登录表单上怎么样?他们一直看到这些。

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 ...
}

What about on a login form? They see those all of the time.

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 ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文