在Unity游戏开发中, 程序的性能极为重要, 而struct在存取数据方面比class更加快速; 了解struct和class的区别能让我们更正确地使用struct.
大伙都知道struct是值类型, class是引用类型, 所以struct的数据分配在栈上面, class的数据在堆上面.
struct不能继承类(以及struct), 不过struct 可以实现接口; 同时struct也是不能被继承的, 因为struct是被类修饰符sealed隐式修饰的;
1.由于struct不能被继承, 所以protected也是被禁止的
2.变量不能在定义时初始化, 必须在构造函数中初始化;
public struct StructB
{
public int b = 2;
public int b2 = 3;
public StructB(int b, int b2)
{
this.b = b;
this.b2 = b2;
}
}
StructB b = new StructB();
Console.WriteLine(b.b);
Console.WriteLine(b.b2);
上面的程序会输出2个0, 并不会输出在定义变量时给的值;
public struct StructB
{
public int b;
public int b2;
public StructB(int b, int b2)
{
this.b = b;
this.b2 = b2;
}
public StructB()
{
b = 11;
b2 = 22;
}
}
StructB b = new StructB();
Console.WriteLine(b.b);
Console.WriteLine(b.b2);
StructB b2 = new StructB(33, 44);
Console.WriteLine(b2.b);
Console.WriteLine(b2.b2);
所以我们可以在构造函数中给变量赋值; 如上程序;
作为成员变量时, struct可以使用protected修饰, 但不在类里时, 是不被允许的
在C++中, struct比C中多了一些语义, 比如C++中是可以有成员函数的, 而C中不能有, 而且C中无法继承struct.
struct与class的不同点:
1.struct默认都是public修饰词, 默认没有封装的概念, 并且继承时也是默认public.
而C++默认都是private修饰, 默认有封装的概念, 并且继承时也是默认private.
2.struct不能用于模板编程, 而class可以.