C# 多類和物件
多個物件
您可以建立同一個類的多個物件
示例
建立兩個 Car
物件
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj1 = new Car();
Car myObj2 = new Car();
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}
使用多個類
您也可以建立一個類的物件並在另一個類中使用它。這通常用於更好地組織類(一個類包含所有欄位和方法,而另一個類包含 Main()
方法(要執行的程式碼))。
- prog2.cs
- prog.cs
prog2.cs
class Car
{
public string color = "red";
}
prog.cs
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
您注意到 public
關鍵字了嗎?它被稱為訪問修飾符,它指定 Car
的 color
變數/欄位也可以被 Program
等其他類訪問。
您將在接下來的章節中學習更多關於訪問修飾符和類/物件的知識。