C# - 检查变量是否已初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12413948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - checking if a variable is initialized
提问by Superbest
I want to check if a variable is initialized at run time, programmatically. To make the reasons for this less mysterious, please see the following incomplete code:
我想以编程方式检查变量是否在运行时初始化。为了让这个原因不那么神秘,请看下面不完整的代码:
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.");
And complete the relevant bit.
并完成相关位。
One hacky solution is to initialize s with a default value:
一个hacky解决方案是用默认值初始化s:
string s = "zanzibar";
And then check if it changed:
然后检查它是否改变:
bool sIsUninitialized = s == "zanzibar";
However, what if someValueor someOtherValuehappen to be "zanzibar" as well? Then I have a bug. Any better way?
但是,如果someValue或someOtherValue碰巧也是“桑给巴尔”呢?然后我有一个错误。有什么更好的办法吗?
采纳答案by McGarnagle
Code won't even compile if the compiler knows a variable hasn't been initialized.
如果编译器知道一个变量没有被初始化,代码甚至不会编译。
string s;
if (condition) s = "test";
// compiler error here: use of unassigned local variable 's'
if (s == null) Console.Writeline("uninitialized");
In other cases you could use the defaultkeyword if a variable may not have been initialized. For example, in the following case:
在其他情况下,default如果变量可能尚未初始化,您可以使用关键字。例如,在以下情况下:
class X
{
private string s;
public void Y()
{
Console.WriteLine(s == default(string)); // this evaluates to true
}
}
The documentationstates that default(T) will give nullfor reference types, and 0for value types. So as pointed out in the comments, this is really just the same as checking for null.
该文档指出默认(T)将给出null对于引用类型和0值类型。正如评论中指出的那样,这实际上与检查 null 相同。
This all obscures the fact that you should really initialize variables, to nullor whatever, when they are first declared.
这一切都掩盖了这样一个事实,即您应该null在首次声明变量时真正将其初始化为或其他。
回答by dasblinkenlight
You can keep a separate flag that indicates that the string has been initialized:
您可以保留一个单独的标志,指示字符串已被初始化:
string s = null;
bool init = false;
if (conditionOne) {
s = someValueOne;
init = true;
}
if (conditionTwo) {
s = someValueTwo;
init = true;
}
if (!init) {
...
}
This will take care of situations when sis assigned, including the cases when it is assigned null, empty string, or "zanzibar".
这将处理s分配时的情况,包括分配时的情况null,空字符串或"zanzibar"。
Another solution is to make a static string to denote "uninitialized" value, and use Object.ReferenceEqualsinstead of ==to check if it has changed. However, the boolvariable approach expresses your intent a lot more explicitly.
另一种解决方案是制作一个静态字符串来表示“未初始化”值,并使用Object.ReferenceEquals而不是==检查它是否已更改。但是,bool变量方法更明确地表达了您的意图。
回答by Sam Axe
I pick initialization values that can never be used, typical values include String.Empty, null, -1, and a 256 character random string generator .
我选择的是永远不能被用来初始化值,典型值包括String.Empty,null,-1,和256个字符的随机字符串发生器。
回答by Vytalyi
Just assign it nullby default, not a string value
只是null默认分配它,而不是字符串值
回答by David W
With C# 2.0, you have the Nullable operator that allows you to set an initial value of null for heretofore value types, allowing for such things as:
在 C# 2.0 中,您有 Nullable 运算符,它允许您为迄今为止的值类型设置 null 的初始值,允许执行以下操作:
int? x = null;
if (x.HasValue)
{
Console.WriteLine("Value for x: " + num.Value);
}
Which yields: "Value for x: Null".
这产生:“x 的值:空”。
回答by Tim Goodman
Here's one way:
这是一种方法:
string s;
if (someCondition) { s = someValue; }
else if (someOtherCondition) { s = someOtherValue; }
else { throw new Exception("Please initialize s."); }
Console.WriteLine(s)
This might be preferable for checking if the string is null, because maybe someValue is a method that can sometimes return null. In other words, maybe null is a legitimate value to initialize the string to.
这对于检查字符串是否为空可能更可取,因为可能 someValue 是有时可以返回空的方法。换句话说,也许 null 是一个合法的值来初始化字符串。
Personally I like this better than an isInitializedflag. Why introduce an extra flag variable unless you have to? I don't think it is more readable.
就我个人而言,我比isInitialized旗帜更喜欢这个。除非必须,为什么要引入额外的标志变量?我不认为它更具可读性。
回答by Peter Gluck
In general, assign the default to be nullor String.Empty. For situations where you cannot use those "empty" values, define a constant to represent your application-specific uninitialized value:
通常,将默认值指定为nullor String.Empty。对于无法使用这些“空”值的情况,请定义一个常量来表示特定于应用程序的未初始化值:
const string UninitializedString = "zanzibar";
Then reference that value whenever you want to initialize or test for initialization:
然后在您想要初始化或测试初始化时引用该值:
string foo = UnininitializedString;
if (foo == UninitiaizedString) {
// Do something
}
Remember that strings are immutable constants in C# so there is really only one instance of UninitializedString(which is why the comparison works).
请记住,字符串在 C# 中是不可变的常量,因此实际上只有一个实例UninitializedString(这就是比较有效的原因)。

