结构是使用 struct 关键字定义的,例如:

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

 结构与类共享大多数相同的语法,但结构比类受到的限制更多:

  • 在结构声明中,除非字段被声明为 const 或 static,否则无法初始化。

  • 结构不能声明默认构造函数(没有参数的构造函数)或析构函数。

  • 在使用值类型的集合(如 Dictionary<string, myStruct>)时,请务必记住这一点。

  • 结构是值类型,而类是引用类型。

  • new 运算符。

  • 结构可以声明带参数的构造函数。

  • System.Object

  • 结构可以实现接口。

  • 结构可用作可以为 null 的类型,因而可向其赋 null 值。

使用结构

Point 的对象,所以本示例中的结构命名为“CoOrds”。

对于任何私有成员或以其他方式设置为不可访问的成员,只能在构造函数中进行初始化。

但是,在初始化所有字段之前,字段将保持未赋值状态且对象不可用。

(这将导致编译器错误 CS0171。)

结构可实现接口,其方式同类完全一样。

值类型。

除非需要引用类型语义,将较小的类声明为结构,可以提高系统的处理效率。

//下面的示例演示使用默认构造函数和参数化构造函数的 struct 初始化。
public struct CoOrds
{
    public int x, y;

    public CoOrds(int p1, int p2)
    {
        x = p1;
        y = p2;
    }
}

// Declare and initialize struct objects.
class TestCoOrds
{
    staticvoid Main()
    {
        // Initialize:   
        CoOrds coords1 = new CoOrds();
        CoOrds coords2 = new CoOrds(10, 10);

        // Display results:
        Console.Write("CoOrds 1: ");
        Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

        Console.Write("CoOrds 2: ");
        Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    CoOrds 1: x = 0, y = 0
    CoOrds 2: x = 10, y = 10
*/

 

相关文章:

  • 2022-12-23
  • 2021-08-16
  • 2022-12-23
  • 2022-03-08
  • 2021-08-03
  • 2021-12-15
  • 2021-07-23
猜你喜欢
  • 2022-12-23
  • 2021-08-24
  • 2021-09-06
  • 2021-05-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案