
与 Java 一样,C# 也有对象和类。对象是现实世界的实体和类的实例。使用对象访问类的成员。
要访问类成员,需要在对象名称后面使用点 (.) 运算符。点运算符将对象的名称与成员的名称链接起来,例如,
Box Box1 = new Box();
在上面你可以看到 Box1 是我们的对象。我们将使用它来访问成员。
Box1.height = 3.0;
您还可以使用它来调用成员函数。
Box1.getVolume();
以下示例展示了对象和类在 C# 中的工作原理。
实时演示
using System;
namespace BoxApplication {
class Box {
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
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) {
// Creating two objects
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// using objects to call the member functions
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}Volume of Box1 : 210 Volume of Box2 : 1560
以上就是C# 中的对象和类有什么区别?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号