在C#3.0中,我喜欢这种风格:
// Write the numbers 1 thru 7
foreach (int index in Enumerable.Range( 1, 7 ))
{
Console.WriteLine(index);
}
Run Code Online (Sandbox Code Playgroud)
在传统的for循环:
// Write the numbers 1 thru 7
for (int index = 1; index <= 7; index++)
{
Console.WriteLine( index );
}
Run Code Online (Sandbox Code Playgroud)
假设'n'很小,所以性能不是问题,是否有人反对传统风格的新风格?
下面的代码是检查执行相同解决方案的三种不同方式的性能.
public static void Main(string[] args)
{
// for loop
{
Stopwatch sw = Stopwatch.StartNew();
int accumulator = 0;
for (int i = 1; i <= 100000000; ++i)
{
accumulator += i;
}
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, accumulator);
}
//Enumerable.Range
{
Stopwatch sw = Stopwatch.StartNew();
var ret = Enumerable.Range(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n);
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret);
}
//self-made IEnumerable<int>
{
Stopwatch sw = Stopwatch.StartNew();
var ret = …Run Code Online (Sandbox Code Playgroud) 我有这个代码块
double[] tabHeight = { 16, 10, 15, 20 };
double[] tabMidSectionWA = { 6, 2, 5, 6 };
double[] tabCurveWA = {
(tabHeight[0] - tabMidSectionWA[0]) / 2 ,
(tabHeight[1] - tabMidSectionWA[1]) / 2,
(tabHeight[2] - tabMidSectionWA[2]) / 2 ,
(tabHeight[3] - tabMidSectionWA[3]) / 2
};
Run Code Online (Sandbox Code Playgroud)
是否有(tabheight - tabMid) / 2使用 for 循环或 foreach的公式添加这些值的更简单方法?