C# 中的類例項有哪些?
類例項是物件。C# 和其他面向物件的語言一樣,也有物件和類。物件是現實世界的實體,而類是物件的例項。用一個物件訪問類的成員。
若要訪問類的成員,可以在物件名稱後面使用點 (.) 運算子。點運算子將物件名稱和成員名稱連結在一起,例如,
Box Box1 = new Box();
上面你可以看到 Box1 是我們的物件。我們將用它來訪問這些成員 −
Box1.height = 7.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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP