C# 元组Tuple

在C# 4.0之前我们函数有多个返回值,通常是使用ref,out 。到了c# 4.0 应当使用元组Tuple而不是使用输出参数,在任何时候都应避免使用ref/out传递参数,尤其对引用类型(禁止引用的引用,尝试改进你的设计。数组合并了相同类型的对象,而元组合并了不同类型的对象。

================DEMO====================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Example
    {
        public static void Main()
        {
            Tuple<string, double, int>[] scores = 
                    { Tuple.Create("Jack", 78.8, 8),
                      Tuple.Create("Abbey", 92.1, 9), 
                      Tuple.Create("Dave", 88.3, 9),
                      Tuple.Create("Sam", 91.7, 8), 
                      Tuple.Create("Ed", 71.2, 5),
                      Tuple.Create("Penelope", 82.9, 8),
                      Tuple.Create("Linda", 99.0, 9),
                      Tuple.Create("Judith", 84.3, 9) };
            var result = ComputeStatistics(scores);
            Console.WriteLine("Mean score: {0:N2} (SD={1:N2}) (n={2})",
                              result.Item2, result.Item3, result.Item1);
            Console.ReadLine();
        
        }

        private static Tuple<int, double, double> ComputeStatistics(Tuple<string, double, int>[] scores)
        {
            int n = 0;
            double sum = 0;

            // 计算平均值,Compute the mean.
            foreach (var score in scores)
            {
                n += score.Item3;
                sum += score.Item2 * score.Item3;
            }
            double mean = sum / n;

            //计算标准偏差. Compute the standard deviation.
            double ss = 0;
            foreach (var score in scores)
            {
                ss += Math.Pow(score.Item2 - mean, 2);
            }
           
            double sd = Math.Sqrt(ss / (scores.Length-1));
            return Tuple.Create(scores.Length, mean, sd);
        }
    }
}

结果:

相关链接:

[你必须知道的.NET]第三十二回,,深入.NET 4.0之,Tuple一二

posted on 2015-01-13 21:48  二狗你变了  阅读(2098)  评论(0)    收藏  举报

导航