类和结构的区别?

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 100 收藏 0 点赞 0 评论 0

类:

类是引用类型在堆上分配,类的实例进行赋值只是复制了引用,都指向同一段实际对象分配的内存

类有构造和析构函数

类可以继承和被继承

结构:

结构是值类型在栈上分配(虽然栈的访问速度比较堆要快,但栈的资源有限放),结构的赋值将分配产生一个新的对象。

结构没有构造函数,但可以添加。结构没有析构函数

结构不可以继承自另一个结构或被继承,但和类一样可以继承自接口

示例:

根据以上比较,我们可以得出一些轻量级的对象最好使用结构,但数据量大或有复杂处理逻辑对象最好使用类。

如:Geoemtry(GIS 里的一个概论,在 OGC 标准里有定义) 最好使用类,而 Geometry 中点的成员最好使用结构

using System;

using System.Collections.Generic;

using System.Text;

namespace Example16

{

interface IPoint

{

double X

{

get;

set;

}

double Y

{

get;

set;

}

double Z

{

get;

set;

}

}

//结构也可以从接口继承

struct Point: IPoint

{

private double x, y, z;

//结构也可以增加构造函数

public Point(double X, double Y, double Z)

{

this.x = X;

this.y = Y;

this.z = Z;

}

public double X

{

get { return x; }

set { x = value; }

}

public double Y

{

get { return x; }

set { x = value; }

}

public double Z

{

get { return x; }

set { x = value; }

}

}

//在此简化了点状Geometry的设计,实际产品中还包含Project(坐标变换)等复杂操作

class PointGeometry

{

private Point value;

public PointGeometry(double X, double Y, double Z)

{

value = new Point(X, Y, Z);

}

public PointGeometry(Point value)

{

//结构的赋值将分配新的内存

this.value = value;

}

public double X

{

get { return value.X; }

set { this.value.X = value; }

}

public double Y

{

get { return value.Y; }

set { this.value.Y = value; }

}

public double Z

{

get { return value.Z; }

set { this.value.Z = value; }

}

public static PointGeometry operator +(PointGeometry Left, PointGeometry Rigth)

{

return new PointGeometry(Left.X + Rigth.X, Left.Y + Rigth.Y, Left.Z + Rigth.Z);

}

public override string ToString()

{

return string.Format(“X: {0}, Y: {1}, Z: {2}”, value.X, value.Y, value.Z);

}

}

class Program

{

static void Main(string[] args)

{

Point tmpPoint = new Point(1, 2, 3);

PointGeometry tmpPG1 = new PointGeometry(tmpPoint);

PointGeometry tmpPG2 = new PointGeometry(tmpPoint);

tmpPG2.X = 4;

tmpPG2.Y = 5;

tmpPG2.Z = 6;

//由于结构是值类型,tmpPG1 和 tmpPG2 的坐标并不一样

Console.WriteLine(tmpPG1);

Console.WriteLine(tmpPG2);

//由于类是引用类型,对tmpPG1坐标修改后影响到了tmpPG3

PointGeometry tmpPG3 = tmpPG1;

tmpPG1.X = 7;

tmpPG1.Y = 8;

tmpPG1.Z = 9;

Console.WriteLine(tmpPG1);

Console.WriteLine(tmpPG3);

Console.ReadLine();

}

}

}

结果:
X: 1, Y: 2, Z: 3
X: 4, Y: 5, Z: 6
X: 7, Y: 8, Z: 9
X: 7, Y: 8, Z: 9

评论列表
文章目录