共用方式為


Structs (C# Programming Guide) 

Structs are defined using the struct keyword, for example:

public struct PostalAddress
{
    // Fields, properties, methods and events go here...
}

Structs share almost all the same syntax as classes, although structs are more limited than classes:

  • Struct instance field declarations cannot use initializers, although static fields on structs can be initialized.

  • A struct may not declare a default constructor —a constructor with no parameters — or a destructor.

Copies of structs are created and destroyed automatically by the compiler, so a default constructor and destructor are unnecessary. In effect, the compiler implements the default constructor by assigning all the fields of their default values (see Default Values Table). Structs cannot inherit from classes or other structs.

Structs are value types — when an object is created from a struct and assigned to a variable, the variable contains the entire value of the struct. When a variable containing a struct is copied, all of the data is copied, and any modification to the new copy does not change the data for the old copy. Because structs do not use references, they do not have identity — there is no way to distinguish between two instances of a value type with the same data. All value types in C# inherently derive from ValueType, which inherits from Object.

Value types can be converted to reference types by the compiler in a process known as boxing. For more information, see Boxing and Unboxing.

Structs Overview

Structs have the following properties:

  • Structs are value types while classes are reference types.

  • When passing a struct to a method, it is passed by value instead of as a reference.

  • Unlike classes, structs can be instantiated without using a new operator.

  • Structs can declare constructors, but they must take parameters.

  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.

  • A struct can implement interfaces.

  • It is an error to initialize an instance field in a struct.

For more information:

See Also

Reference

Objects, Classes and Structs (C# Programming Guide)

Concepts

C# Programming Guide
Classes (C# Programming Guide)