C# - 检查变量是否已初始化

标签 c# initialization

我想检查一个变量是否在运行时以编程方式初始化。为了让这个原因不那么神秘,请看下面不完整的代码:

string s;

if (someCondition) s = someValue;
if (someOtherCondition) s = someOtherValue;

bool sIsUninitialized = /* assign value correctly */;

if (!sIsUninitialized) Console.WriteLine(s) else throw new Exception("Please initialize s.");

并完成相关位。

一个 hacky 解决方案是用默认值初始化 s:

string s = "zanzibar";

然后检查它是否改变了:

bool sIsUninitialized = s == "zanzibar";

但是,如果 someValuesomeOtherValue 恰好也是“zanzibar”怎么办?然后我有一个错误。有什么更好的方法吗?

最佳答案

如果编译器知道变量没有被初始化,代码甚至不会编译。

string s;
if (condition) s = "test";
// compiler error here: use of unassigned local variable 's'
if (s == null) Console.Writeline("uninitialized");

在其他情况下,如果变量可能尚未初始化,您可以使用 default 关键字。例如,在以下情况中:

class X
{ 
    private string s;
    public void Y()
    {
        Console.WriteLine(s == default(string));  // this evaluates to true
    }
}

documentation声明 default(T) 将为引用类型提供 null,为值类型提供 0。因此,正如评论中所指出的,这实际上与检查 null 相同。


这一切都掩盖了一个事实,即当变量首次声明时,您应该真正将变量初始化为 null 或其他任何内容。

关于C# - 检查变量是否已初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413948/

相关文章:

c# - 如何在WPF中绘制一个可点击的矩形

c# - Win10 构建 : Loading assembly failed

c# - 在这个给定的案例中遵循什么 url 重写或通配符子域规则?

c# - 停止/启动后 URI 的注册已经存在

c# - 初始化语法 : new ViewDataDictionary { { "Name", "Value"} }

c - C中结构数组的静态初始化

ios - 在objective-c中初始化一个类别

c# - 在 MSI 安装程序中使用 C# 创建自定义对话框

ios - 将成员初始化为类函数导致 'self' used in method call错误

java - Java 中的双括号初始化是什么?