c# - 当我尝试在 if() 中使用变量时,它说我正在使用未分配的变量

标签 c# multithreading

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/

相关文章:

c# - 在 C# 程序中存储查询的正确方法是什么?

c# - 如何在 EF Core Like 函数中使用通配符

c# - VB6 到 C# : Loop or Index Issue?

c++ - 终止在不同 QThread 中运行的 QProcess

c# - 服务器控件、客户端控件、面板、默认按钮和客户端事件

c# - C# 中的路径 MTU 发现

c++ - ZMQ异步,具体是如何工作的?

c++ - Windows 线程-C++

java - 为什么使用线程池时看不到性能提升?

multithreading - 循环时更新PyQt4 GUI