類別 (C# 程式設計手冊)Classes (C# Programming Guide)

參考型別Reference types

定義為 class 的類型即為「參考型別」**。A type that is defined as a class is a reference type. 在執行階段,當您宣告參考型別的變數時,該變數會包含 null 值,直到您使用 new 運算子明確地建立類別的執行個體,或為其指派在他處建立的相容類型物件為止,如下列範例所示:At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the class by using the new operator, or assign it an object of a compatible type that may have been created elsewhere, as shown in the following example:

//Declaring an object of type MyClass.
MyClass mc = new MyClass();

//Declaring another object of the same type, assigning it the value of the first object.
MyClass mc2 = mc;

建立物件時,會在受控堆積上配置足夠的記憶體給該特定物件,而變數只會保留該物件位置的參考。When the object is created, enough memory is allocated on the managed heap for that specific object, and the variable holds only a reference to the location of said object. 配置以及由 CLR 的自動記憶體管理功能 (也就是「記憶體回收」**) 回收 Managed 堆積上的類型時,都需要額外負荷。Types on the managed heap require overhead both when they are allocated and when they are reclaimed by the automatic memory management functionality of the CLR, which is known as garbage collection. 不過,記憶體回收也已獲得高度最佳化,因此在大部分情況下並不會產生效能問題。However, garbage collection is also highly optimized and in most scenarios, it does not create a performance issue. 如需記憶體回收的詳細資訊,請參閱自動記憶體管理和記憶體回收For more information about garbage collection, see Automatic memory management and garbage collection.

宣告類別Declaring Classes

使用 class 關鍵字並在後面接著唯一識別碼來宣告類別,如下列範例所示:Classes are declared by using the class keyword followed by a unique identifier, as shown in the following example:

//[access modifier] - [class] - [identifier]
public class Customer
   // Fields, properties, methods and events go here...

class 關鍵字的前面會加上存取層級。The class keyword is preceded by the access level. 因為在此情況下會使用 public,所以所有人都可以從這個類別建立執行個體。Because public is used in this case, anyone can create instances of this class. 類別的名稱遵循 class 關鍵字。The name of the class follows the class keyword. 類別名稱必須是有效的 C# 識別碼名稱The name of the class must be a valid C# identifier name. 定義的其餘部分是定義行為和資料的類別主體。The remainder of the definition is the class body, where the behavior and data are defined. 類別上的欄位、屬性、方法和事件統稱為「類別成員」**。Fields, properties, methods, and events on a class are collectively referred to as class members.

建立物件Creating objects

雖然它們有時會交換使用,但是類別和物件不同。Although they are sometimes used interchangeably, a class and an object are different things. 類別會定義一種類型的物件,但不是物件本身。A class defines a type of object, but it is not an object itself. 物件是根據類別的具體實體,而且有時稱為類別的執行個體。An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class.

使用後面接著為物件基礎之類別名稱的 new 關鍵字,即可建立物件,與下面類似:Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:

Customer object1 = new Customer();

建立類別的執行個體時,會將物件的參考傳回給程式設計人員。When an instance of a class is created, a reference to the object is passed back to the programmer. 在上述範例中,object1 是根據 Customer 之物件的參考。In the previous example, object1 is a reference to an object that is based on Customer. 這個參考參照新的物件,但不包含物件資料本身。This reference refers to the new object but does not contain the object data itself. 事實上,您可以建立物件參考,而根本不需要建立物件︰In fact, you can create an object reference without creating an object at all:

 Customer object2;

不建議建立物件參考,例如未參照物件的物件參考,因為在執行階段嘗試透過這類參考來存取物件將會失敗。We don't recommend creating object references such as this one that don't refer to an object because trying to access an object through such a reference will fail at run time. 不過,可以進行這類參考來參照某個物件,方法是建立新的物件,或將它指派給現有物件,如下︰However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:

Customer object3 = new Customer();
Customer object4 = object3;

這個程式碼會建立同時參照相同物件的兩個物件參考。This code creates two object references that both refer to the same object. 因此,任何透過 object3 進行的物件變更都會反映在後續使用 object4 時。Therefore, any changes to the object made through object3 are reflected in subsequent uses of object4. 因為以傳址方式參照根據類別的物件,所以類別稱為參考型別。Because objects that are based on classes are referred to by reference, classes are known as reference types.

類別繼承Class inheritance

類別完全支援「繼承」**,這是物件導向程式設計的基礎特性。Classes fully support inheritance, a fundamental characteristic of object-oriented programming. 當您建立類別時,可以繼承自任何未定義為 sealed 的介面或類別,而其他類別可以繼承自您的類別並覆寫類別虛擬方法。When you create a class, you can inherit from any other interface or class that is not defined as sealed, and other classes can inherit from your class and override class virtual methods.

使用「衍生」** 可完成繼承,這表示使用從中繼承資料和行為的「基底類別」** 來宣告類別。Inheritance is accomplished by using a derivation, which means a class is declared by using a base class from which it inherits data and behavior. 附加冒號以及接著衍生類別名稱後面的基底類別名稱,以指定基底類別,與下面類似:A base class is specified by appending a colon and the name of the base class following the derived class name, like this:

public class Manager : Employee
    // Employee fields, properties, methods and events are inherited
    // New Manager fields, properties, methods and events go here...

類別宣告基底類別時,會繼承基底類別的所有成員,但建構函式除外。When a class declares a base class, it inherits all the members of the base class except the constructors. 如需詳細資訊,請參閱繼承For more information, see Inheritance.

與 C++ 不同,C# 中的類別只能直接繼承自一個基底類別。Unlike C++, a class in C# can only directly inherit from one base class. 不過,因為基底類別本身可以繼承自另一個類別,所以類別可能會間接繼承多個基底類別。However, because a base class may itself inherit from another class, a class may indirectly inherit multiple base classes. 基至,類別可以直接實作多個介面。Furthermore, a class can directly implement more than one interface. 如需詳細資訊,請參閱介面For more information, see Interfaces.

類別可以宣告為 abstractA class can be declared abstract. 抽象類別包含具有簽章定義但沒有實作的抽象方法。An abstract class contains abstract methods that have a signature definition but no implementation. 無法具現化抽象類別。Abstract classes cannot be instantiated. 它們僅用於實作抽象方法的衍生類別。They can only be used through derived classes that implement the abstract methods. 相較之下,sealed 類別不允許從它衍生其他類別。By contrast, a sealed class does not allow other classes to derive from it. 如需詳細資訊,請參閱 抽象和密封類別和類別成員For more information, see Abstract and Sealed Classes and Class Members.

類別定義可以在不同的原始程式檔之間進行分割。Class definitions can be split between different source files. 如需詳細資訊,請參閱部分類別和方法For more information, see Partial Classes and Methods.


下列範例定義了一個公用類別,其中包含自動實作屬性、方法以及稱為建構函式的特殊方法。The following example defines a public class that contains an auto-implemented property, a method, and a special method called a constructor. 如需詳細資訊,請參閱屬性方法建構函式主題。For more information, see Properties, Methods, and Constructors topics. 然後使用 new 關鍵字具現化類別的執行個體。The instances of the class are then instantiated with the new keyword.

using System;

public class Person
    // Constructor that takes no arguments:
    public Person()
        Name = "unknown";

    // Constructor that takes one argument:
    public Person(string name)
        Name = name;

    // Auto-implemented readonly property:
    public string Name { get; }

    // Method that overrides the base class (System.Object) implementation.
    public override string ToString()
        return Name;
class TestPerson
    static void Main()
        // Call the constructor that has no parameters.
        var person1 = new Person();

        // Call the constructor that has one parameter.
        var person2 = new Person("Sarah Jones");
        // Get the string representation of the person2 instance.

        Console.WriteLine("Press any key to exit.");
// Output:
// unknown
// Sarah Jones
// Sarah Jones

C# 語言規格C# Language Specification

如需詳細資訊,請參閱 c # 語言規格For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also