为什么我总是需要在实际使用它进行比较之前为字符串变量赋值。 例如: 一些输入 - obj
string temp;
if (obj== null)
{
temp = "OK";
}
string final = temp;
我收到编译时错误 - 类似于 - 无法使用未分配的变量“temp”。但是字符串变量的默认值为“null”,我想使用它。那么为什么这是不允许的呢?
最佳答案
when default is null
局部变量的默认值是不 null(或其他任何值)。它只是未分配。
您可能正在考虑字符串字段(类级别的变量)。那将是 null
:
private string temp;
private void M()
{
if (obj== null)
{
temp = "OK";
}
string final = temp; // default tnull
}
但在方法内部,只需使用您需要的值进行初始化:
string temp = null;
关于c# - 为什么在比较之前为字符串赋值,默认为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12913785/