如果要写入(首次读取之前),是否需要初始化局部变量?

rex*_*ghk -1 c#

我看到了很多具有以下结构的代码:

public void Blah()
{
    int a = 0;
    string b = "";
    DateTime c = DateTime.MinValue;
    bool d = false;
    // ...More initializations with dummy values

    // Overwrite the values in a, b, c, d, e.g. a = ReturnInt();

    // Do calculations, reading the values from a, b, c, d, like DoCalculations(a);
}
Run Code Online (Sandbox Code Playgroud)

一般来说,我更喜欢这样的东西:

public void Blah()
{
    int a = GetInt();
    string b = GetString();
    DateTime c = GetDateTime();
    bool d = GetBool();

    // Do calculations, reading the values from a, b, c, d, like DoCalculations(a);
}
Run Code Online (Sandbox Code Playgroud)

这真的是必要的,并且由于额外的初始化会有任何性能命中吗?

Kar*_*k T 5

变量应该在使用之前初始化,如果该用法是a,read如果你要在初始化后立即覆盖它,最好遵循你显示的第二种样式,主要是为了可读性目的,我期望性能命中(来自样式#1)如果任何通常都是最小的.