为什么我总是需要在实际使用它来进行比较之前为字符串变量赋值.例如:一些输入 - 对象
string temp;
if (obj== null)
{
temp = "OK";
}
string final = temp;
Run Code Online (Sandbox Code Playgroud)
我得到编译时错误 - 类似于 - 无法使用未分配的变量'temp'.但是字符串变量的默认值为'null',我想使用它.那为什么不允许这样做呢?
当default为null时
对于局部变量,默认值不为 null(或其他任何内容).它只是未分配.
您可能正在考虑字符串字段(类级别的变量).那将是null:
private string temp;
private void M()
{
if (obj== null)
{
temp = "OK";
}
string final = temp; // default tnull
}
Run Code Online (Sandbox Code Playgroud)
但是在方法中,只需使用您需要的值进行初始化:
string temp = null;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |