变量的初始化:直接还是在构造函数中? [英] Initialization of variables: Directly or in the constructor?

查看:85
本文介绍了变量的初始化:直接还是在构造函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

大多数时候,我看到初始化这样的变量的方式

Most of the time, I see the way of initializing a variable like this

public class Test
{
    private int myIntToInitalize;

    public Test()
    {
        myIntToInitalize = 10;
    }
}

在我看来,这是最通用的初始化变量。书籍,博客和.NET的内部实现中的大多数代码都与我的示例等效。

From my perspective, this is the most general way of initializing a variable. Most of the code in books, blogs and also internal implementations of .NET are equivalent to my example.

最近,我看到人们直接进行初始化,因此没有设置值在构造函数中。

Recently I saw people doing the initialization directly, so without setting the value in the constructor.

public class Test
{
    private int myIntToInitalize = 10;
}

从角度来看,初始化和声明变量还是声明变量在构造函数中初始化变量。

In point of view, there is not difference whether initialize and declare a variable or initialize the variable in the constructor.

除了最佳实践和代码行的长度之外,直接初始化变量的好处在哪里,并且有细微的差别吗?

Apart from the best practices and the length of code lines, where are the benefits of initialize a variable directly and are there subtle differences?

推荐答案

在某些情况下可能存在一个显着的差异。

There's one potentially significant difference in some cases.

实例初始化程序在执行基类构造函数。因此,如果基类构造函数调用派生类中重写的任何虚拟方法,则该方法将看到不同之处。 通常不应有明显的区别,因为在构造函数中调用虚拟方法几乎总是一个坏主意。

Instance initializers are executed before the base class constructor is executed. So if the base class constructor invokes any virtual methods which are overridden in the derived class, that method will see the difference. Usually this shouldn't be a noticeable difference, however - as invoking virtual methods in a constructor is almost always a bad idea.

为了清楚起见,如果在声明时初始化变量,则可以很清楚地看到值取决于任何构造函数参数。另一方面,将所有初始化都放在一起也有助于提高可读性,IMO。我会尝试确保在可能的情况下,如果您有多个构造函数,它们都将委派给一个主构造函数,该构造函数执行所有真实初始化-这意味着您只会将这些分配放入

In terms of clarity, if you initialize the variable at the point of declaration, it makes it very clear that the value doesn't depend on any constructor parameters. On the other hand, keeping all the initialization together helps readability too, IMO. I would try to make sure that wherever possible, if you have multiple constructors they all delegate to one "master" constructor which does all the "real" initialization - which means you'll only put those assignments in one place either way.

示例代码演示区别:

using System;

class Base
{
    public Base()
    {
        Console.WriteLine(ToString());
    }
}

class Derived : Base
{
    private int x = 5;
    private int y;

    public Derived()
    {
        y = 5;
    }

    public override string ToString()
    {
        return string.Format("x={0}, y={1}", x, y);
    }
}

class Test
{
    static void Main()
    {
        // Prints x=5, y=0
        new Derived();
    }
}

这篇关于变量的初始化:直接还是在构造函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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