C# 類成員
類成員
類中的欄位和方法通常被稱為“類成員”。
示例
建立一個 Car
類,包含三個類成員:兩個欄位和一個方法。
// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Fields
在上一章中,您瞭解到類中的變數稱為欄位,並且可以透過建立類的物件並使用點語法(.
)來訪問它們。
以下示例將建立一個名為 myObj
的 Car
類物件。然後,我們將列印 color
和 maxSpeed
欄位的值。
示例
class Car
{
string color = "red";
int maxSpeed = 200;
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
您也可以將欄位留空,並在建立物件時修改它們。
示例
class Car
{
string color;
int maxSpeed;
static void Main(string[] args)
{
Car myObj = new Car();
myObj.color = "red";
myObj.maxSpeed = 200;
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
這在建立類的多個物件時尤其有用。
示例
class Car
{
string model;
string color;
int year;
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
物件方法
您從C# 方法章節瞭解到,方法用於執行某些操作。
方法通常屬於一個類,並且它們定義了類物件的行為。
與欄位一樣,您可以使用點語法訪問方法。但是,請注意,該方法必須是 public
的。並且請記住,我們使用方法的名稱後跟兩個括號 ()
和一個分號 ;
來呼叫(執行)該方法。
示例
class Car
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
Car myObj = new Car();
myObj.fullThrottle(); // Call the method
}
}
為什麼我們將方法宣告為 public
,而不是像C# 方法章節中的示例那樣宣告為 static
?
原因很簡單:static
方法可以在不建立類的物件的情況下進行訪問,而 public
方法只能由物件訪問。
使用多個類
請記住,從上一章開始,我們可以使用多個類以獲得更好的組織(一個用於欄位和方法,另一個用於執行)。這是推薦的做法。
prog2.cs
class Car
{
public string model;
public string color;
public int year;
public void fullThrottle()
{
Console.WriteLine("The car is going as fast as it can!");
}
}
prog.cs
class Program
{
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
public
關鍵字稱為訪問修飾符,它指定 Car
的欄位也可以被其他類(如 Program
)訪問。
您將在後面的章節中瞭解更多關於訪問修飾符的內容。