问题
Consider the following snippets:
void Foo(object sender, EventArgs e)
{
if (!(sender is ComboBox comboBox)) return;
comboBox.DropDownWidth = 100;
}
compared to
void Bar(object sender, EventArgs e)
{
if ((sender is ComboBox comboBox) == false) return;
comboBox.DropDownWidth = 100;
}
Code including Foo()
successfully compiles in .Net 4.6.1, while code including Bar()
results in Use of unassigned local variable 'comboBox'
.
Without getting into a debate over the reasons behind using == false
instead of the negation operator, can someone explain why one compiles and the other does not?
回答1:
Updated Answer Thanks to Julien opening a GitHub issue.
See Neal Gafter's response (copied here from here):
However, the error you're seeing is not about scope. It is about definite assignment. A pattern variable is definitely assigned when the pattern-matching expression is true. The unary ! operator reverses assigned-when-true and assigned-when-false. However, the boolean equality operator == throws away the distinction between assigned-when-true and assigned-when-false.
I believe the comboBox
variable will only be created if the pattern matches.
来源:https://stackoverflow.com/questions/49523905/inline-variable-declaration-doesnt-compile-when-using-false-instead-of-neg