初始分配的变量和初始未分配的变量之间的核心区别是什么?C# [英] What is the core difference between an intially assigned variable and a initially unassigned variable? C#

查看:63
本文介绍了初始分配的变量和初始未分配的变量之间的核心区别是什么?C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Microsoft文档将其描述为:

变量是初始分配的或初始未分配的.初始分配的变量具有定义明确的初始值,并且始终被视为绝对分配的变量.最初未分配的变量没有初始值.

Variables are either initially assigned or initially unassigned. An initially assigned variable has a well-defined initial value and is always considered definitely assigned. An initially unassigned variable has no initial value.

但这实际上是什么意思?

是否只是简单地声明何时声明一个变量,要么为其分配了值(即,最初为该变量分配了一个值),还是没有为其分配值(即,该变量最初未被分配).

Is it simply stating when a variable is declared it's either assigned a value (i.e., such a variable is an initially assigned a value) or not (i.e., such a variable is initially unassigned).

我的假设正确吗?

推荐答案

是的,这只是一个声明.两者之间没有任何重大差异.程序运行时,将使用数据类型的默认值初始化未分配的变量.唯一会遇到未分配变量的问题的情况是,如果在 if 块中分配该变量,并且没有 else 语句,然后尝试在外部使用该变量 if 块的范围.在这种情况下,编译器将引发错误,指出该变量可能未分配.例如:

Yes it is just a statement. There are not any major differences between the two. Unassigned variables are initialized with the default value for the data type when the program runs. The only time you will run into an issue with unassigned variables is if you assign it in if blocks and don't have an else statement and then attempt to use the variable outside the scope of the if block. The compiler will throw an error saying that the variable is potentially unassigned in this case. Ex:

string testString;
if (some condition here)
    testString = "Success";

if (testString == "Success") //This line will throw an error because testString may be unassigned

string testString = "Failure";
if (condition)
    testString = "Success";

if (testString == "Success") //No error this time becuase testString was initialized with a value

string testString;
if (condition)
    testString = "Success";
else
    testString = "Failure";

if (testString == "Success") //No error here because all paths will assign a value to testString

从Microsoft
初始分配的变量
以下变量类别被分类为最初分配的变量:

Edit from Microsoft:
Initially assigned variables
The following categories of variables are classified as initially assigned:

  • 静态变量.
  • 类实例的实例变量.
  • 最初分配的结构变量的实例变量.
  • 数组元素.
  • 值参数.
  • 参考参数.
  • 在catch子句或foreach语句中声明的变量.

最初未分配的变量
以下类别的变量分类为最初未分配的变量:

Initially unassigned variables
The following categories of variables are classified as initially unassigned:

  • 最初未分配的结构变量的实例变量.
  • 输出参数,包括struct实例的this变量构造函数.
  • 局部变量,但在catch子句或foreach语句.
public static int globalId; //assigned
public class TestClass
{
    int Id; //Assigned
    public void TestMethod()
    {
        int methodId; //Not assigned
    }
}

这篇关于初始分配的变量和初始未分配的变量之间的核心区别是什么?C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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