struct 构造函数

今天写了个struct,像在创建的时候初始化:

代码
class Program
{
static void Main(string[] args)
{

p2 ppp
= new p2();

}

struct p2
{
public int pX, pY;

public p2()
{
this.pX = 0;
this.pY = 0;
}
}
}

编译出错,呀哈。 Structs cannot contain explicit parameterless constructors。不包括无参的构造器。

那好给一个:

  

struct p2
{
public int pX, pY;

public p2(int x)
{
this.pX =x;
//this.pY = 0;
}
}

  呀哈,又错。 Field 'CsharpProj.Program.p2.pY' must be fully assigned before control is returned to the caller 

pY没有初始化。怎么回事,class是可以的呀。查查.net 框架:

C#不允许值类型定义无参构造函数是为了消除开发人员对于何时调用它们产生的混淆,……没有无参构造器,值类型的字段总是被初始化为0或null。另外由于可验证代码要求所有的值类型字段在被读之前首先进行初始化,所以我们为值类型定义的任何构造器都必须要初始化其所有的字段。

至此,一切真相大白。都是C#搞得鬼。不知道C++里是什么样的?

  

原文地址:https://www.cnblogs.com/jimson/p/Vtor.html