我的代码如下
int tmpCnt;
if (name == "Dude")
tmpCnt++;
Run Code Online (Sandbox Code Playgroud)
为什么会出错Use of unassigned local variable tmpCnt?我知道我没有明确初始化它,但由于默认值表,0无论如何都会初始化值类型.该参考文献也提醒我:
请记住,不允许在C#中使用未初始化的变量.
但是,如果它已经默认完成,为什么我必须明确地这样做?如果我不必这样做,它会不会获得性能?就是想...
我在C#中有两个相似的结构,每个结构都包含一个整数,但后者有实现的get/set访问器.
为什么在分配字段之前必须Y使用new运算符初始化struct a?是y仍然当我初始化它的值类型new?
public struct X
{
public int a;
}
public struct Y
{
public int a { get; set; }
}
class Program
{
static void Main(string[] args)
{
X x;
x.a = 1;
Y y;
y.a = 2; // << compile error "unused local variable" here
Y y2 = new Y();
y2.a = 3;
}
}
Run Code Online (Sandbox Code Playgroud)