我在 C# 中遇到了一个奇怪的行为
以下代码无法编译
dynamic? x;
//... initialize x
if(x is {} y && y.z == 1){
Console.WriteLine(y);
}
WriteLine 中出现错误
use of unassigned local variable y
但是以下所有变体都可以编译
dynamic? x;
if(x is {} y){
if(y.z == 1){
Console.WriteLine(y);
}
}
dynamic? x;
if(x is object y && y.z == 1){
Console.WriteLine(y);
}
mytype? x; //mytype is a class that defines an int z
if(x is {} y && y.z == 1){
Console.WriteLine(y);
}
那么
dynamic
、is {}
的组合以及使用单个 if 会导致无法编译,有什么特别之处?
我的观点可能是错误的,但我认为可以编译其他变体,因为 x 没有在那里初始化。所以
x is {}
总是返回 false。所以其他带有 y
的代码甚至无法编译,因为它永远不会被使用