struct 类型是一种值类型,通常用来封装小型相关变量组,例如,矩形的坐标或书籍的一些基本特征。 例如:
public struct Book
{
public string Name;
public decimal Price;
public string Author;
public string Publisher;
}
结构还可以包含构造函数、常量、字段、方法、属性、索引器、运算符、事件和嵌套类型,但如果同时需要上述几种成员,则应当考虑改为使用类作为类型。
struct
- strust 和 class差不多,但有些不同
- struct是值类型,class是引用类型
- struct不支持继承(出来隐式的继承了object,System.ValueType)
struct 成员
- class能有的成员struct也可以有,但是有以下几个不行:
- 无参构造函数
- 字段初始化器
- 终结器
- virtual或者protect成员(因为struct不支持继承,所以这两个就没有意义)
struct的构建
- struct 有一个构造函数,但是你不能对其重写。它会对字段进行按位归零操作。
- 当你定义struct构造函数的时候,必须显示的为每个字段赋值。
- 不可以有字段初始化器。
例子
public struct Point
{
int x, y;
public Point(int x,int y)
{
this.x = x;
this.y = y;
}
}
Point point1 = new Point();//point1.x=0,point1.y=0
Point point2 = new Point(7,7);//point2.x=7,point2.y=7
错误的例子
public struct Point
{
int x = 1; //struct中不能进行字段初始化
int y;
public Point() { } //不能使用无参构造函数
public Point(int x) { this.x = x; } //当你定义struct构造函数的时候,必须显示的为每个字段赋值
}