C#变量初始化问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/952503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:06:53  来源:igfitidea点击:

C# Variable Initialization Question

c#initializationdefault-value

提问by coson

Is there any difference on whether I initialize an integer variable like:

我是否初始化一个整数变量,如:

int i = 0;
int i;

Does the compiler or CLR treat this as the same thing? IIRC, I think they're both treated as the same thing, but I can't seem to find the article.

编译器或 CLR 是否将其视为同一件事?IIRC,我认为它们都被视为同一件事,但我似乎找不到这篇文章。

采纳答案by TheSean

I looked at the IL (using ildasm) and its true that only the int set to 0 is really set to 0 in the constructor.

我查看了 IL(使用 ildasm),确实只有设置为 0 的 int 在构造函数中才真正设置为 0。

public class Class1
{
    int setToZero = 0;
    int notSet;
}

Generates:

产生:

.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       15 (0xf)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.0
  IL_0002:  stfld      int32 ClassLibrary1.Class1::setToZero
  IL_0007:  ldarg.0
  IL_0008:  call       instance void [mscorlib]System.Object::.ctor()
  IL_000d:  nop
  IL_000e:  ret
} // end of method Class1::.ctor

回答by Brandon

Yes, it pretty much is the same thing.

是的,它几乎是一样的。

You can refer to this article on Coding Horror

你可以参考这篇关于Coding Horror 的文章

回答by heavyd

As the following link states, they are exactly the same:

正如以下链接所述,它们完全相同:

http://msdn.microsoft.com/en-us/library/aa664742%28VS.71%29.aspx

http://msdn.microsoft.com/en-us/library/aa664742%28VS.71%29.aspx

回答by Michael Todd

If the variable iis an instance variable, it will be assigned the value 0 automatically. If it is a local variable in a method, it is undefined, so you would need to assign it a value before using it.

如果变量i是一个实例变量,它会被自动赋值为 0。如果它是方法中的局部变量,则它是未定义的,因此您需要在使用之前为其分配一个值。

For example:

例如:

class Program
{
    static void Main(string[] args)
    {
        intTest it;

        it = new intTest();

        Console.ReadLine();
    }

    class intTest
    {
        int i;

        public intTest()
        {
            int i2;

            Console.WriteLine("i = " + i);
            Console.WriteLine("i2 = " + i2);
        }
    }
}

The above will not compile because i2 is unassigned. However, by assigning 0 to i2, i.e.

上面不会编译,因为 i2 是未分配的。但是,通过将 0 分配给 i2,即

int i2 = 0;

and compiling, then running, will show that both are now assigned 0.

编译,然后运行,将显示两者现在都被分配了 0。

回答by Reed Copsey

Any time you create a type in C#, it automatically gets filled in with padded zeros. In the case of a class (reference type), this equates to a null pointer. So, technically, any time you're working with classes, the following are identical:

每当您在 C# 中创建类型时,它都会自动填充填充零。在类(引用类型)的情况下,这等同于空指针。因此,从技术上讲,无论何时您使用类,以下内容都是相同的:

MyClass class;
MyClass class2 = null;

With value types (any struct, including int/float/double/etc), the type is passed with zeros, so the following are equivalent:

对于值类型(任何结构,包括 int/float/double/etc),类型以零传递,因此以下是等效的:

int i;
int j = 0;

However, in a method, the compiler checks to see if you've assigned a value to your types prior to using it. If you do the following, the compiler will complain:

但是,在方法中,编译器会在使用之前检查您是否已将值分配给您的类型。如果您执行以下操作,编译器会抱怨:

int i;
Console.WriteLine{"{0}",i);

Technically, the above should be fine - but since it's a common source of programmer error, the compiler specifically checks for unassigned local variables, and complains. However, this is a compile-time complaint, and not a CLR issue. You can make IL that does the above, and it runs fine.

从技术上讲,以上应该没问题 - 但由于它是程序员错误的常见来源,编译器专门检查未分配的局部变量,并发出抱怨。但是,这是编译时投诉,而不是 CLR 问题。您可以使 IL 执行上述操作,并且运行良好。

回答by Lloyd McFarlin

These are only equivalent for fields (class variables). Fields are automatically assigned the default values when the class is initialized. Within a method or property, the unassigned variable remains unassigned and will cause a compiler error if you try to access it's value.

这些仅对字段(类变量)等效。初始化类时,字段会自动分配默认值。在方法或属性中,未分配的变量保持未分配状态,如果您尝试访问它的值,则会导致编译器错误。

回答by Brian Hinchey

With all this talk, it is worth mentioning the "default" keyword in C#.

说了这么多,值得一提的是 C# 中的“default”关键字。

I.e. int i;is equivalent to int i = default(int);which is equivalent to int i = 0;and MyClass o = default(MyClass);is equivalent to MyClass o = null;

int i;相当于int i = default(int);相当于int i = 0;MyClass o = default(MyClass);相当于MyClass o = null;

This is especially relevant when using linq methods such as .SingleOrDefault()because you can always use the following to make your code more readable:

这在使用 linq 方法时尤其重要,.SingleOrDefault()因为您始终可以使用以下内容使您的代码更具可读性:

int someValue = collection.<various linq methods>.SingleOrDefault();
if (someValue == default(int))
{
  //Code for the default case
}

and

MyClass someValue = collection.<various linq methods>.SingleOrDefault();
if (someValue == default(MyClass))
{
  //Code for the default case
}

回答by Vinicius

Various responses here are kind of misleading, including the referenced article in "Coding Horror" website.

这里的各种回复都具有误导性,包括“编码恐怖”网站中引用的文章。

The compiler will optimize your code to remove all "unnecessary" initializations when configured to optimize the generated code. Please notice that this is the default behavior when compiling in "Release" mode.

当配置为优化生成的代码时,编译器将优化您的代码以删除所有“不必要的”初始化。请注意,这是在“发布”模式下编译时的默认行为。

I, for one, think it's always very useful to initialize all your variables. The performance hit will be minimal in debug mode and none in release mode, but the gains of explicitly set the variables will be tremendous for anyone maintaining the code in the future, in the better "documenting code with code" style. I remember this very experienced coworker of mine that thought that the default value of Int32 was Int32.MinValue instead of 0. These types of confusion always happens to things implicited in the code and, to me, they should be avoided in most cases.

一方面,我认为初始化所有变量总是非常有用的。在调试模式下性能损失最小,在发布模式下没有,但是显式设置变量的收益对于将来维护代码的任何人来说都是巨大的,以更好的“用代码记录代码”风格。我记得我这个非常有经验的同事认为 Int32 的默认值是 Int32.MinValue 而不是 0。这些类型的混淆总是发生在代码中隐含的事情上,对我来说,在大多数情况下应该避免它们。