C#struct关键字(补充)
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/194
struct和class差不多,但是有一些不同:
✦ struct是值类型,class是引用类型
✦ struct不支持继承(除了隐式继承了object,具体点就是System.ValueType)
class能有的成员,struct也可以有,但是以下几个不行:
✦ 无参构造函数
✦ 字段初始化器
✦ 终结器
✦ virtual或protected成员
注意点
✦ struct有一个无参的构造函数,但是你不能对其重写,它会对字段进行按位归零操作。
✦ 当你定义struct构造函数的时候,必须显式地为每个字段赋值。
✦ 不可以有字段初始化器。
正确例子:
public struct Point
{
int x,y;
public Point(int x,int y){this.x=x;this,y=y}
}…
Point p1=new Point(); //p1.x and p1.y will be 0
Point p2=new Point(1,1); //p1.x and p1.y will be 1
错误例子:
public struct Point
{
int x=1; //非法:初始化字段
int y;
public Point(){} //非法:初始化无参构造函数
public Point(int x){this.x=x;} //非法:未初始化y
}
This article was last edited at 2020-03-14 13:42:34