即使更冗长,在 foreach 之外定义变量是否是更好的编码实践? [英] Is it better coding practice to define variables outside a foreach even though more verbose?

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

问题描述

在以下示例中:

  • 第一个看起来更冗长但不浪费资源
  • 第二个不那么冗长,但更浪费资源(每个循环重新定义字符串)
  • the first seems more verbose but less wasteful of resources
  • the second is less verbose but more wasteful of resources (redefines string each loop)

哪种编码习惯更好?

第一个例子:

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();
        }
    }
}

第二个例子:

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.

(请注意,通常这不会造成行为上的差异,但如果变量被 lambda 表达式或匿名方法捕获,则情况并非如此.)

(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 之外定义变量是否是更好的编码实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆