類別和結構 (c # 程式設計手冊) Classes and structs (C# programming guide)

類別和結構是 .NET 中一般型別系統的兩個基本結構。Classes and structs are two of the basic constructs of the common type system in .NET. 每一個基本上都是封裝一組屬於相同邏輯單元之資料和行為的資料結構。Each is essentially a data structure that encapsulates a set of data and behaviors that belong together as a logical unit. 資料和行為是類別或結構的「成員」**,它們包含類別或結構的方法、屬性和事件等,如本主題稍後所列。The data and behaviors are the members of the class or struct, and they include its methods, properties, and events, and so on, as listed later in this topic.

類別或結構宣告就像是用來在執行階段建立執行個體或物件的藍圖。A class or struct declaration is like a blueprint that is used to create instances or objects at run time. 如果您定義稱為 Person 的類別或結構,Person 將會是型別的名稱。If you define a class or struct called Person, Person is the name of the type. 如果您宣告並初始化型別 Person 的變數 pp 即為 Person 的物件或執行個體。If you declare and initialize a variable p of type Person, p is said to be an object or instance of Person. 您可以建立多個相同 Person 型別的執行個體,且每個執行個體在其屬性與欄位中都可以有不同的值。Multiple instances of the same Person type can be created, and each instance can have different values in its properties and fields.

類別是參考型別。A class is a reference type. 當建立類別的物件時,物件指派至的變數僅會保留該記憶體的參考。When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. 當物件參考指派至新的變數時,新的變數會參考到原始物件。When the object reference is assigned to a new variable, the new variable refers to the original object. 透過某個變數所做的變更會反映在其他變數中,因為它們都參考相同的資料。Changes made through one variable are reflected in the other variable because they both refer to the same data.

結構是實值型別。A struct is a value type. 當建立結構時,結構指派至的變數會保留結構的實際資料。When a struct is created, the variable to which the struct is assigned holds the struct's actual data. 將結構指派至新的變數時,將會複製結構。When the struct is assigned to a new variable, it is copied. 因此,新的變數和原始變數會各自包含一份相同的資料。The new variable and the original variable therefore contain two separate copies of the same data. 針對其中一個複本所做的變更,並不會影響到另一個複本。Changes made to one copy do not affect the other copy.

一般情況下,類別會用來建立更複雜行為的模型,或是要在建立類別物件後修改之資料的模型。In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. 結構最適合小型資料結構,該結構主要包含不會在結構建立後修改的資料。Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

如需詳細資訊,請參閱 類別物件結構類型For more information, see Classes, Objects, and Structure types.


在下列範例中,ProgrammingGuide 命名空間中的 CustomClass 有三個成員:執行個體建構函式、名稱為 Number 的屬性,以及名稱為 Multiply 的方法。In the following example, CustomClass in the ProgrammingGuide namespace has three members: an instance constructor, a property named Number, and a method named Multiply. Main類別中的方法 Program 會建立 (物件) 的實例 CustomClass ,並使用點標記法來存取物件的方法和屬性。The Main method in the Program class creates an instance (object) of CustomClass, and the object's method and property are accessed by using dot notation.

using System;

namespace ProgrammingGuide
   // Class definition.
   public class CustomClass
      // Class members.
      // Property.
      public int Number { get; set; }

      // Method.
      public int Multiply(int num)
          return num * Number;

      // Instance Constructor.
      public CustomClass()
          Number = 0;

   // Another class definition that contains Main, the program entry point.
   class Program
      static void Main(string[] args)
         // Create an object of type CustomClass.
         CustomClass custClass = new CustomClass();

         // Set the value of the public property.
         custClass.Number = 27;

         // Call the public method.
         int result = custClass.Multiply(4);
         Console.WriteLine($"The result is {result}.");
// The example displays the following output:
//      The result is 108.


「封裝」** 有時被稱為物件導向程式設計的第一大支柱或原則。Encapsulation is sometimes referred to as the first pillar or principle of object-oriented programming. 根據封裝原則,類別或結構可以指定其各個成員針對類別或結構外部之程式碼的存取程度。According to the principle of encapsulation, a class or struct can specify how accessible each of its members is to code outside of the class or struct. 不應該在類別或組件之外使用的方法和變數,可隱藏以限制程式碼錯誤或惡意攻擊的可能性。Methods and variables that are not intended to be used from outside of the class or assembly can be hidden to limit the potential for coding errors or malicious exploits.

如需有關類別的詳細資訊,請參閱類別物件For more information about classes, see Classes and Objects.


所有的方法、欄位、常數、屬性和事件都必須在型別內宣告。這些便是該型別的「成員」**。All methods, fields, constants, properties, and events must be declared within a type; these are called the members of the type. 和部分其他語言不同,在 C# 中並沒有全域變數或方法。In C#, there are no global variables or methods as there are in some other languages. 即使是程式的進入點 (Main 方法),也必須在類別或結構內宣告。Even a program's entry point, the Main method, must be declared within a class or struct. 下列清單包含所有可能在類別或結構中宣告的各種成員。The following list includes all the various kinds of members that may be declared in a class or struct.


有些方法和屬性必須從類別或結構以外的程式碼呼叫或存取,它們稱為「用戶端程式碼」**。Some methods and properties are meant to be called or accessed from code outside your class or struct, known as client code. 其他方法和屬性可能只會在類別或結構本身中使用。Other methods and properties might be only for use in the class or struct itself. 請務必限制程式碼的可存取性,以確保只有目標用戶端程式碼可以存取。It is important to limit the accessibility of your code so that only the intended client code can reach it. 您可以使用存取修飾詞 publicprotectedinternalprotected internalprivateprivate protected,來指定用戶端程式碼可以存取您的類型和其成員的程度。You specify how accessible your types and their members are to client code by using the access modifiers public, protected, internal, protected internal, private and private protected. 預設可存取性為 privateThe default accessibility is private. 如需詳細資訊,請參閱存取修飾詞For more information, see Access Modifiers.


類別 (而不是結構) 支援繼承的概念。Classes (but not structs) support the concept of inheritance. 衍生自另一個類別 (「基底類別」**) 的類別,會自動包含基底類別的所有 public、protected 和 internal 成員 (其建構函式和完成項除外)。A class that derives from another class (the base class) automatically contains all the public, protected, and internal members of the base class except its constructors and finalizers. 如需詳細資訊,請參閱繼承多型For more information, see Inheritance and Polymorphism.

類別可宣告為抽象,這表示其一或多個方法沒有任何實作。Classes may be declared as abstract, which means that one or more of their methods have no implementation. 雖然抽象類別無法直接具現化,但是它們可以做為其他能提供遺失實作之類別的基底類別。Although abstract classes cannot be instantiated directly, they can serve as base classes for other classes that provide the missing implementation. 類別也可以宣告為密封,以防止其他類別繼承它們。Classes can also be declared as sealed to prevent other classes from inheriting from them. 如需詳細資訊,請參閱 抽象和密封類別和類別成員For more information, see Abstract and Sealed Classes and Class Members.


類別和結構可以繼承多個介面。Classes and structs can inherit multiple interfaces. 繼承介面表示型別會實作介面中定義的所有方法。To inherit from an interface means that the type implements all the methods defined in the interface. 如需詳細資訊,請參閱介面For more information, see Interfaces.

泛型型別Generic Types

類別和結構可以使用一或多個型別參數加以定義。Classes and structs can be defined with one or more type parameters. 當用戶端程式碼建立型別的執行個體時,便會提供型別。Client code supplies the type when it creates an instance of the type. 例如, System.Collections.Generic 命名空間中的 List<T> 類別是以一個型別參數來定義。For example The List<T> class in the System.Collections.Generic namespace is defined with one type parameter. 用戶端程式碼會建立 List<string>List<int> 的執行個體,以指定清單將保留的型別。Client code creates an instance of a List<string> or List<int> to specify the type that the list will hold. 如需詳細資訊,請參閱泛型For more information, see Generics.

靜態型別Static Types

類別 (而不是結構) 可以宣告為靜態Classes (but not structs) can be declared as static. 靜態類別僅可以包含靜態成員,且無法使用新的關鍵字具現化。A static class can contain only static members and cannot be instantiated with the new keyword. 類別的其中一個複本會在程式載入時載入至記憶體,其成員會透過類別名稱存取。One copy of the class is loaded into memory when the program loads, and its members are accessed through the class name. 類別和結構都可以包含靜態成員。Both classes and structs can contain static members. 如需詳細資訊,請參閱 靜態類別和靜態類別成員For more information, see Static Classes and Static Class Members.

巢狀類型Nested Types

類別或結構能以巢狀方式置於另一個類別或結構內。A class or struct can be nested within another class or struct. 如需詳細資訊,請參閱 巢狀型別For more information, see Nested Types.

部分型別Partial Types

您可以在某個程式碼檔案中定義類別、結構或方法的某個部分,並在另一個程式碼檔案中定義另一部分。You can define part of a class, struct or method in one code file and another part in a separate code file. 如需詳細資訊,請參閱部分類別和方法For more information, see Partial Classes and Methods.

物件初始設定式Object Initializers

您可以具現化及初始化類別或結構物件,以及物件的集合,而不用明確地呼叫其建構函式。You can instantiate and initialize class or struct objects, and collections of objects, without explicitly calling their constructor. 如需詳細資訊,請參閱物件和集合初始設定式For more information, see Object and Collection Initializers.

匿名類型Anonymous Types

在不方便或不必要建立具名類別的情況下 (例如當您使用不必保存或傳遞到另一個方法的資料結構填入清單時),可以使用匿名型別。In situations where it is not convenient or necessary to create a named class, for example when you are populating a list with data structures that you do not have to persist or pass to another method, you use anonymous types. 如需詳細資訊,請參閱 匿名型別For more information, see Anonymous Types.

擴充方法Extension Methods

您可以透過建立其方法能以該方法屬於原始型別之方式呼叫的個別型別,在不必建立衍生類別的情況下「擴充」類別。You can "extend" a class without creating a derived class by creating a separate type whose methods can be called as if they belonged to the original type. 如需詳細資訊,請參閱擴充方法For more information, see Extension Methods.

隱含類型區域變數Implicitly Typed Local Variables

在類別或結構方法內,您可以使用隱含型別來指示編譯器在編譯時間判斷正確的型別。Within a class or struct method, you can use implicit typing to instruct the compiler to determine the correct type at compile time. 如需詳細資訊,請參閱隱含型別區域變數For more information, see Implicitly Typed Local Variables.

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