当我尝试在if()中使用一个变量时,它表示我正在使用一个未分配的变量
本文关键字:变量 一个 表示 分配 if | 更新日期: 2023-09-27 18:00:02
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")
当您像这样分配x1时
string x1;
Dispatcher.Invoke(new Action (() => x1 = lbl1.Content.ToString()));
您正在另一个线程上分配x1,但编译器无法检测到您的变量已被分配。
尝试为x1设置一个默认值,这将修复问题
String x1 = "";
希望它能帮助
来自Compiler Error CS0165
C#编译器不允许使用未初始化的变量。如果编译器检测到使用的变量可能不是初始化后,它生成编译器错误
您声明了x1
变量,但没有初始化它。可能需要像;
string x1 = "";
或
string x1 = null;
编译器没有意识到您正在分配x1,因为这不是一个直接的分配。因此,只需更改这一行:
string x1 = null; // or assign a different default value
仔细想想,您使用的是多线程。
- 在线程A上,您声明
x1
- 在线程A上,您正在尝试使用
x1
- 在线程B上分配
x1
现在,事件的顺序是什么?会是1 > 3> 2
吗?编译器为什么要这么认为
如果它将是1 >2 >3
,则意味着您试图在分配x1
之前使用它,而这正是编译器所抱怨的。
由于在不同线程中分配x1
,因此主线程中x1
未分配
您可以通过在声明x1
时将null
分配给x1
来更正它
string x=null;