【发布时间】:2020-06-05 10:18:28
【问题描述】:
public static void Main()
{
int n;
//n++; Of course it would cause 'Use of unassigned local variable error' compiler error.
int.TryParse("not an int", out n); //not assignig here
n++; //now legal. Why?
System.Console.WriteLine(n); //1
}
我不明白为什么这段代码会这样。一开始它不允许使用未分配的变量,但在 TryParse 之后它允许使用,尽管 TryParse 没有为变量分配任何东西。在某些时候变量被分配给默认值 0(我想从一开始)但是这种行为的逻辑和解释是什么?
【问题讨论】:
-
你知道什么时候方法有
out参数然后它必须分配一些东西吗? ...所以在SomeMethod(out n)-n总是被分配之后......并且 TryParse 不给变量分配任何东西 不是真的 -
out 参数修饰符。
标签: c# variable-assignment theory