类和结构(C# 编程指南)Classes and Structs (C# Programming Guide)

类和结构是 .NET Framework 通用类型系统的两种基本构造。Classes and structs are two of the basic constructs of the common type system in the .NET Framework. 每种本质上都是一种数据结构,其中封装了同属一个逻辑单元的一组数据和行为。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 类型的变量 p,那么 p 就是所谓的 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 Structs.

示例Example

在以下示例中,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. Program 类中的 Main 方法创建 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

封装有时称为面向对象的编程的第一支柱或原则。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.

成员Members

所有方法、字段、常量、属性和事件都必须在类型中进行声明;这些被称为类型的成员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.

可访问性Accessibility

一些方法和属性可供类或结构外部的代码(称为“客户端代码”)调用或访问。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.

继承Inheritance

类(而非结构)支持继承的概念。Classes (but not structs) support the concept of inheritance. 派生自另一个类(基类 )的类自动包含基类的所有公共、受保护和内部成员(其构造函数和终结器除外)。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.

可以将类声明为 abstract,即一个或多个方法没有实现代码。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. 类还可以声明为 sealed,以阻止其他类继承。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.

接口Interfaces

类和结构可以继承多个接口。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

类(而非结构)可以声明为 staticClasses (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