Practical example where Tuple can be used in .Net 4.0?

后端 未结 19 733
后悔当初
后悔当初 2020-12-04 07:44

I have seen the Tuple introduced in .Net 4 but I am not able to imagine where it can be used. We can always make a Custom class or Struct.

19条回答
  •  天涯浪人
    2020-12-04 07:54

    Tuples are great for doing multiple async IO operations at a time and returning all the values together. Here is the examples of doing it with and without Tuple. Tuples can actually make your code clearer!

    Without (nasty nesting!):

    Task.Factory.StartNew(() => data.RetrieveServerNames())
        .ContinueWith(antecedent1 =>
            {
                if (!antecedent1.IsFaulted)
                {
                    ServerNames = KeepExistingFilter(ServerNames, antecedent1.Result);
                    Task.Factory.StartNew(() => data.RetrieveLogNames())
                        .ContinueWith(antecedent2 =>
                            {
                                if (antecedent2.IsFaulted)
                                {
                                    LogNames = KeepExistingFilter(LogNames, antecedent2.Result);
                                    Task.Factory.StartNew(() => data.RetrieveEntryTypes())
                                        .ContinueWith(antecedent3 =>
                                            {
                                                if (!antecedent3.IsFaulted)
                                                {
                                                    EntryTypes = KeepExistingFilter(EntryTypes, antecedent3.Result);
                                                }
                                            });
                                }
                            });
                }
            });
    

    With Tuple

    Task.Factory.StartNew(() =>
        {
            List serverNames = data.RetrieveServerNames();
            List logNames = data.RetrieveLogNames();
            List entryTypes = data.RetrieveEntryTypes();
            return Tuple.Create(serverNames, logNames, entryTypes);
        }).ContinueWith(antecedent =>
            {
                if (!antecedent.IsFaulted)
                {
                    ServerNames = KeepExistingFilter(ServerNames, antecedent.Result.Item1);
                    LogNames = KeepExistingFilter(LogNames, antecedent.Result.Item2);
                    EntryTypes = KeepExistingFilter(EntryTypes, antecedent.Result.Item3);
                }
            });
    

    If you were using an anonymous function with an implied type anyway then you aren't making the code less clear by using the Tuple. Retuning a Tuple from a method? Use sparingly when code clarity is key, in my humble opinion. I know functional programming in C# is hard to resist, but we have to consider all of those old clunky "object oriented" C# programmers.

提交回复
热议问题