2024-11-08
类
定义一个类要有关键字class
,类的方法其实不必多说,class
前面可以加上默认成员访问标识符private
、public
、internal
等。
成员函数和封装
封装就是将变量定义为私有,只有通过公共函数才能进行访问,就像下面这段代码就是一个例子:
using System; | |
namespace BoxApplication | |
{ | |
class Box | |
{ | |
private double length; // 长度 | |
private double breadth; // 宽度 | |
private double height; // 高度 | |
public void setLength( double len ) | |
{ | |
length = len; | |
} | |
public void setBreadth( double bre ) | |
{ | |
breadth = bre; | |
} | |
public void setHeight( double hei ) | |
{ | |
height = hei; | |
} | |
public double getVolume() | |
{ | |
return length * breadth * height; | |
} | |
} | |
class Boxtester | |
{ | |
static void Main(string[] args) | |
{ | |
Box Box1 = new Box(); // 声明 Box1,类型为 Box | |
Box Box2 = new Box(); // 声明 Box2,类型为 Box | |
double volume; // 体积 | |
// Box1 详述 | |
Box1.setLength(6.0); | |
Box1.setBreadth(7.0); | |
Box1.setHeight(5.0); | |
// Box2 详述 | |
Box2.setLength(12.0); | |
Box2.setBreadth(13.0); | |
Box2.setHeight(10.0); | |
// Box1 的体积 | |
volume = Box1.getVolume(); | |
Console.WriteLine("Box1 的体积: {0}" ,volume); | |
// Box2 的体积 | |
volume = Box2.getVolume(); | |
Console.WriteLine("Box2 的体积: {0}", volume); | |
Console.ReadKey(); | |
} | |
} |
构造函数
构造函数就是一个与类同名还没有任何返回值的函数。我们也可以进行参数化构造函数,这样就可以在构造函数里给对象赋予初始值。
using System; | |
namespace LineApplication | |
{ | |
class Line | |
{ | |
private double length; // 线条的长度 | |
public Line(double len) // 参数化构造函数 | |
{ | |
Console.WriteLine("对象已创建,length = {0}", len); | |
length = len; | |
} | |
public void setLength( double len ) | |
{ | |
length = len; | |
} | |
public double getLength() | |
{ | |
return length; | |
} | |
static void Main(string[] args) | |
{ | |
Line line = new Line(10.0); | |
Console.WriteLine("线条的长度: {0}", line.getLength()); | |
// 设置线条长度 | |
line.setLength(6.0); | |
Console.WriteLine("线条的长度: {0}", line.getLength()); | |
Console.ReadKey(); | |
} | |
} | |
} |
析构函数
析构函数就是构造函数前面加一个~
,可以记住这个顺口溜:先构造的后析构,后构造的先析构。
静态成员
静态成员的关键字是static
,静态变量可在成员函数或类的定义外部进行初始化。你也可以在类的定义内部初始化静态变量。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)