(1) 结构体是值类型,它可以包含数据和方法;类是引用类型
(2) 结构体是值类型,不要求堆分配
(3) 结构体存储自身的数据在结构体中,而类存储一个动态对象的引用
(4) 结构体通常用于较小的数据结构
(5) 结构体会影响性能
(7) 构造函数是由新操作符调用的,但是其不会分配在堆上
(8) 一个结构体构造函数直接返回结构体值本身(存储在栈的临时位置),该值
在必要时被拷贝
(9) 对类而言,多个变量可以使用同一个对象的引用
(10)对类而言,对一个变量的操作可能会影响到相同引用的其它变量;但是对结构体而言不是
(11)结构体不支持特定的继承,隐式地继承类型对象
Demo
//PointStruct
Public Struct PointStruct
{
public int x;
public int y;
public PointStruct(int x, int y)
{
this.x=x;
this.y=y;
}
}
//PointClass
class PointClass(int x,int y)
{
public int x;
public int y;
public PointClass(int x,int y)
{
this.x=x;
this.y=y;
}
}
//Main Method
static void Main(string[] args)
{
PointStruct structPoint = new PointStruct();
structPoint.x = 10;
structPoint.y = 10;
Console.WriteLine("初始化结构体的值是" + structPoint.x +"," + structPoint.y);
ModifyStructPoint(structPoint);
Console.WriteLine("改后的结构体的值是" + structPoint.x +"," + structPoint.y);
Console.WriteLine();
PointClass classPoint = new PointClass(10,10);
Console.WriteLine("初始化类的值是" + classPoint.x +"," + classPoint.y);
ModifyClassPoint(classPoint);
Console.WriteLine("改后的类的值是" + classPoint.x +"," + classPoint.y);
Console.WriteLine();
}
//Method
static void ModifyStructPoint(PointStruct newStruct)
{
newStruct.x=20;
newStruct.y=20;
Console.WriteLine("执行ModifyStructPoint方法");
Console.WriteLine("修改的值是" + classPoint.x +"," + classPoint.y);
}
static void ModifyClassPoint(PointStruct newClass)
{
newClass.x=20;
newClass.y=20;
Console.WriteLine("执行ModifyStructPoint方法");
Console.WriteLine("修改的值是" + newClass.x +"," + newClass.y);
}
结果是:
10,10
20,20
10,10
10,10
20,20
20,20
何时使用Class?何时使用Struct?,布布扣,bubuko.com