初始分配变量和初始未分配变量之间的核心区别是什么? C#
What is the core difference between an intially assigned variable and a initially unassigned variable? C#
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.
但这到底是什么意思呢?
它只是简单地说明当一个变量被声明时,它要么被赋值(即,这样的变量最初被赋值),要么没有(即,这样的变量最初未被赋值)。
我的假设正确吗?
是的,这只是一个声明。两者之间没有任何重大差异。未分配的变量在程序 运行s 时使用数据类型的默认值初始化。如果你在 if
块中分配它并且没有 else
语句然后尝试在范围之外使用变量,那么你唯一一次 运行 会遇到未分配变量的问题if
块的。编译器将抛出一个错误,指出在这种情况下该变量可能未分配。例如:
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
来自微软的编辑:
最初分配的变量
以下变量类别 class 初始分配:
- 静态变量。
- class 个实例的实例变量。
- 初始分配的结构变量的实例变量。
- 数组元素。
- 值参数。
- 参考参数。
- 在 catch 子句或 foreach 语句中声明的变量。
最初未分配的变量
以下类别的变量被 class 确定为最初未分配:
- 最初未分配的结构变量的实例变量。
- 输出参数,包括struct实例的this变量
构造函数。
- 局部变量,除了在 catch 子句或
foreach 语句。
public static int globalId; //assigned
public class TestClass
{
int Id; //Assigned
public void TestMethod()
{
int methodId; //Not assigned
}
}
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.
但这到底是什么意思呢?
它只是简单地说明当一个变量被声明时,它要么被赋值(即,这样的变量最初被赋值),要么没有(即,这样的变量最初未被赋值)。
我的假设正确吗?
是的,这只是一个声明。两者之间没有任何重大差异。未分配的变量在程序 运行s 时使用数据类型的默认值初始化。如果你在 if
块中分配它并且没有 else
语句然后尝试在范围之外使用变量,那么你唯一一次 运行 会遇到未分配变量的问题if
块的。编译器将抛出一个错误,指出在这种情况下该变量可能未分配。例如:
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
来自微软的编辑:
最初分配的变量
以下变量类别 class 初始分配:
- 静态变量。
- class 个实例的实例变量。
- 初始分配的结构变量的实例变量。
- 数组元素。
- 值参数。
- 参考参数。
- 在 catch 子句或 foreach 语句中声明的变量。
最初未分配的变量
以下类别的变量被 class 确定为最初未分配:
- 最初未分配的结构变量的实例变量。
- 输出参数,包括struct实例的this变量 构造函数。
- 局部变量,除了在 catch 子句或 foreach 语句。
public static int globalId; //assigned
public class TestClass
{
int Id; //Assigned
public void TestMethod()
{
int methodId; //Not assigned
}
}