为什么必须初始化C#局部变量? [英] Why C# local variables must be initialized?

查看:253
本文介绍了为什么必须初始化C#局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读MCTS自定进度培训套件(70-536)第2版,在第一章中,我们有以下内容。

I am reading MCTS Self Paced Training Kit (70-536) Edition 2 and in the 1st chapter we have the following.


如何声明值类型变量
要使用类型,必须首先将
a符号声明为实例这种类型的。
值类型具有隐式
构造函数,因此声明
会自动实例化该类型;
不需要像上课那样包含New
关键字。
构造函数为新的
实例分配默认值
(通常为null或0),但是您应该始终
在声明中显式初始化变量
,例如在
中显示以下代码块:

How to Declare a Value Type Variable To use a type, you must first declare a symbol as an instance of that type. Value types have an implicit constructor, so declaring them instantiates the type automatically; you don’t have to include the New keyword as you do with classes. The constructor assigns a default value (usually null or 0) to the new instance, but you should always explicitly initialize the variable within the declaration, as shown in the following code block:



'VB

Dim b As Boolean = False    

// C#  
bool b = false;

但是,当我编译以下控制台应用程序时,

However, when I compile the following Console Application,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ch1_70_536
{
    class Program
    {
        static void Main(string[] args)
        {
            bool b;
            Console.WriteLine("The value of b is " + b);
            Console.ReadKey();
        }
    }
}

我收到编译时间错误


使用未分配的局部变量b

"Use of Unassigned Local Variable b"

勘误表中甚至没有提及。我是在做错事还是书完全错了?

It is not even mentioned in the Errata. Am I doing something wrong or is the book completely wrong?

推荐答案

关于VB,这本书基本上是正确的,但是

The book is mostly correct when it comes to VB, but it fails to mention the difference between VB and C# in this case.

在VB中,所有局部变量都会自动初始化:

In VB all local variables are automatically initialised:

Sub Test()
  Dim x As Integer
  MessageBox.Show(x.ToString()) 'shows "0"
End Sub

虽然在C#中未初始化局部变量,但在以下情况下,编译器不允许您使用它们:

While in C# local variables are not initialised, and the compiler won't let you use them until they are:

void Test() {
  int x;
  MessageBox.Show(x.ToString()); // gives a compiler error
}

此外,尚不清楚这本书实际上是在谈论局部变量或类成员变量。

Also, it's not clear whether the quote from the book is actually talking about local variables or class member variables. Class member variables are always initialised when the class instance is created, both in VB and C#.

这本书是错误的,当它说值类型具有一个隐式构造函数。。那明显是错的。值类型被初始化为其默认值(如果已初始化),并且在发生这种情况时不会调用构造函数。

The book is wrong when it says that "Value types have an implicit constructor". That is simply not true. A value type is initialised to its default value (if it's initialised), and there is no call to a constructor when that happens.

这篇关于为什么必须初始化C#局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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