类
  定义一个类要有关键字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,静态变量可在成员函数或类的定义外部进行初始化。你也可以在类的定义内部初始化静态变量。
来源链接:https://www.cnblogs.com/dmx-03/p/18638787










没有回复内容