网站小图标素材,自己做的网站怎么样合法,河北建设厅查询官方网站,微信电脑版下载官网前言在Dotnet开发过程中#xff0c;Average作为IEnumerable的扩展方法#xff0c;十分常用。本文对Average方法的关键源码进行简要分析#xff0c;以方便大家日后更好的使用该方法。使用Average 计算数值序列的平均值假如我们有这样的一个集合Listint grades new L… 前言在Dotnet开发过程中Average作为IEnumerable的扩展方法十分常用。本文对Average方法的关键源码进行简要分析以方便大家日后更好的使用该方法。使用Average 计算数值序列的平均值假如我们有这样的一个集合Listint grades new Listint { 78, 92, 100, 37, 81 };不使用linq我们要计算该集合的平均值且不能使用linq那么我们的计算平均值方法和下面这段代码应该没有多大的出入double Average(Listint source){if (source null){throw new Exception(集合不能为空);}long sum 0L;long count 0L;foreach (var item in source){sum item;count;}if (count 0){throw new Exception(无元素);}return (double)sum / (double)count;
}使用linqdouble average grades.Average();源码解析方法public static double Average(this IEnumerableint source)参数source 元素的类型返回值double源码:public static double Average(this IEnumerableint source){if (source null){throw new Exception(source is null);}long num 0L;long num2 0L;checked{foreach (int item in source){num item;num2;}if (num2 0){return (double)num / (double)num2;}throw new Exception(NoElements);}}将上述代码放到cheked块里面就会使运行时引发System.OverflowException异常。这样就可以让你的运算更加准确避免二进制的回绕。Enumerable.Average() 重载方法一共十多个,这里选择了最典型的一个讲解总结文章来源于即兴发挥本篇就说到这里啦希望对您有帮助。