string x1;
Dispatcher.Invoke(new Action (() => x1 = lbl1.Content.ToString()));
(我这样做是因为我正在使用线程) (然后当我尝试在 if 中使用它时)
if(x1 == "X"){}
(我收到一条错误消息,说我正在使用未分配的变量)
有人能告诉我为什么会这样吗?
最佳答案
参见:
string x1; // <- Just declared, not assigned
// x1 is assigned, but in the different thread
Dispatcher.Invoke(new Action (() => x1 = lbl1.Content.ToString()));
// it may occure, that the diffrent thread hasn't finished yet, and
// x1 is still unassigned; that's why the compiler shows the warning
if(x1 == "X"){}
然而,在某些情况下,编译器不能跟踪赋值,例如
String x1;
Action f =
() => { x1 = "X"; };
f(); // <- x1 will be assigned here
// Compiler erroneously warns here that x1 is unassigned,
// but x1 is assigned
if (x1 == "X")
关于c# - 当我尝试在 if() 中使用变量时,它说我正在使用未分配的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23261213/