using System;
namespace Structure
{
//结构适用于适合复制值的“轻量级”概念,而类适用于不适合复制值的“重量级”概念
//1.构造函数
//1-1.C#不允许值类型拥有无参构造器:是因为编译器在编译过程中始终为结构采用一个默认的构造函数,
// 编译器为结构采用的默认构造函数,总是将字段初始化为0、false或者null。
//1-2.值类型的构造器必须初始化值类型的所有字段
//1-3.执行值类型上定义的构造器的唯一方法是编写代码显示地调用这些构造器
//2.值类型字段的初始化
//2-1.在值类型的定义中,不能初始化实例字段,但可以初始化静态字段
//2-2.值类型是嵌套在引用类型内部的字段时,值类型字段会保证为0或null,
// 但是基于堆栈的值类型的字段不能保证为0或null。
// 因此,可验证代码要求任何基于堆栈的值类型的字段被读取之前必须进行初始化(进行赋值或调用构造函数)。
struct Pointx
{
int m_x;
int m_y;
}
struct Point
{
public int m_x;
public int m_y;
//2-1.值类型中不能初始化实例字段,但可以初始化静态字段
//public int m_y = 2;
//和类一样,大多数时候都不建议将一个结构的字段声明为public字段,因为无法保证字段总是包含有效的值。
public static int ID = 1;
//1-1.C#不允许值类型拥有无参构造器
// public Point()
// {
// m_x = 2;
// m_y = 3;
// }
//1-2.值类型的构造器必须初始化值类型的所有字段
public Point(int x,int y)
{
m_x = x;
//m_y = y;
m_y = y;
}
public int Mul()
{
return this.m_x * this.m_y;
}
}
internal sealed class Rectangle
{
//值类型是嵌套在引用类型内部的字段时,值类型字段会保证为0或null
public Point m_topLeft;
public Point m_bottomRight;
public Rectangle()
{
}
//显示地调用值类型构造器,初始化值类型的字段(赋值)
public Rectangle(bool flag)
{
if (flag)
{
m_topLeft =new Point(1,2);
m_bottomRight = new Point(100,200);
}
}
}
class Structure
{
static void Main(string[] args)
{
//2-2.值类型是嵌套在引用类型内部的字段时,值类型字段会保证为0,false或null
Rectangle rectangle = new Rectangle();
System.Console.WriteLine("rectangle.m_topLeft.m_x = {0}",rectangle.m_topLeft.m_x);
System.Console.WriteLine();
rectangle.m_bottomRight.Mul();
rectangle = new Rectangle(true);
System.Console.WriteLine("rectangle.m_topLeft.m_x = {0}",rectangle.m_topLeft.m_x);
System.Console.WriteLine();
//不需要调用构造函数就可以创建struct类型的变量,
//但结构的所有字段将保持未初始化的状态,试图访问这些字段中的值时,会引起编译时错误。
Point point ;
//2-2基于堆栈的值类型的字段不能保证为0或null,
//可验证代码要求任何基于堆栈的值类型的字段被读取之前必须进行初始化(赋值)
point.m_x = 2;
System.Console.WriteLine("point.m_x = {0}",point.m_x);
//System.Console.WriteLine("point.m_x = {0}",point.m_y);
System.Console.WriteLine();
//1-3.执行值类型上定义的构造器的唯一方法是编写代码显示地调用这些构造器
//显示调用默认的构造函数
point = new Point();
System.Console.WriteLine("point.m_x = {0}",point.m_x);
System.Console.WriteLine("point.m_y = {0}",point.m_y);
System.Console.WriteLine();
//显示调用自定义构造器
point = new Point(3,4);
System.Console.WriteLine("point.m_x = {0}",point.m_x);
System.Console.WriteLine("point.m_y = {0}",point.m_y);
System.Console.WriteLine();
//可以将一个Sruct变量a赋值于另一个Sruct变量b,但前提是Sruct变量a已经完全初始化。
Point point1 = point;
int y = point1.Mul();
}
}
}