本文介绍了它更好的编码实践,以一个foreach之外定义变量,即使更详细的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子:




  • 第一似乎更冗长,但资源浪费更少

  • 第二看起来更简洁,但更浪费资源(重新定义字符串中的每个循环)



哪一个更好的编码实践



第一个例子:

 使用系统; 
使用System.Collections.Generic;

命名空间TestForeach23434
{
类节目
{
静态无效的主要(字串[] args)
{
名单,LT;字符串>名称=新的List<串GT; {一,二,二,三,四,四};

串TEST1 =;
串TEST2 =;
串TEST3 =;
的foreach(在名称变量名称)
{
= TEST1名+1;
test2的名字= +2;
TEST3 =名+3;
Console.WriteLine({0},{1},{2},为test1,test2的,TEST3);
}
到Console.ReadLine();
}
}
}



第二个例子:

 使用系统; 
使用System.Collections.Generic;

命名空间TestForeach23434
{
类节目
{
静态无效的主要(字串[] args)
{
名单,LT;字符串>名称=新的List<串GT; {一,二,二,三,四,四};

的foreach(在名称变量名称)
{
线测试1 =名+1;
线测试2 =名+2;
串TEST3 =名+3;
Console.WriteLine({0},{1},{2},为test1,test2的,TEST3);
}
到Console.ReadLine();
}
}
}


解决方案

第二种形式是没有更多的浪费 - 这简直是更好的。



除非你想保持与他们的价值观有没有优势,宣布外循环的变量,迭代。



(请注意,一般的,这没有行为差异,但如果变量被一个lambda表达式或匿名抓获这不是真的方法。)


In the following examples:

  • the first seems more verbose but less wasteful of resources
  • the second is less verbose but more wasteful of resources (redefines string each loop)

Which is better coding practice?

First example:

using System;
using System.Collections.Generic;

namespace TestForeach23434
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string> { "one", "two", "two", "three", "four", "four" };

            string test1 = "";
            string test2 = "";
            string test3 = "";
            foreach (var name in names)
            {
                test1 = name + "1";
                test2 = name + "2";
                test3 = name + "3";
                Console.WriteLine("{0}, {1}, {2}", test1, test2, test3);
            }
            Console.ReadLine();
        }
    }
}

Second example:

using System;
using System.Collections.Generic;

namespace TestForeach23434
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string> { "one", "two", "two", "three", "four", "four" };

            foreach (var name in names)
            {
                string test1 = name + "1";
                string test2 = name + "2";
                string test3 = name + "3";
                Console.WriteLine("{0}, {1}, {2}", test1, test2, test3);
            }
            Console.ReadLine();
        }
    }
}
解决方案

The second form is no more wasteful - it's simply better.

There's no advantage to declaring the variables outside the loop, unless you want to maintain their values between iterations.

(Note that usually this makes no behavioural difference, but that's not true if the variables are being captured by a lambda expression or anonymous method.)

这篇关于它更好的编码实践,以一个foreach之外定义变量,即使更详细的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:31