深入解析C#编程中struct所定义的结构

2019-12-30 11:36:36王旭

如果使用 new 运算符创建结构对象,则会创建该结构对象,并调用适当的构造函数。与类不同,结构的实例化可以不使用 new 运算符。在此情况下不存在构造函数调用,因而可以提高分配效率。但是,在初始化所有字段之前,字段将保持未赋值状态且对象不可用。
当结构包含引用类型作为成员时,必须显式调用该成员的默认构造函数,否则该成员将保持未赋值状态且该结构不可用。(这将导致编译器错误 CS0171。)
对于结构,不像类那样存在继承。一个结构不能从另一个结构或类继承,而且不能作为一个类的基。但是,结构从基类 Object 继承。结构可实现接口,其方式同类完全一样。
无法使用 struct 关键字声明类。在 C# 中,类与结构在语义上是不同的。结构是值类型,而类是引用类型。

除非需要引用类型语义,将较小的类声明为结构,可以提高系统的处理效率。
示例 1
描述
下面的示例演示使用默认构造函数和参数化构造函数的 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
{
 static void 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();
 }
}

 

输出:


 CoOrds 1: x = 0, y = 0
 CoOrds 2: x = 10, y = 10

示例 2
描述
下面举例说明了结构特有的一种功能。它在不使用 new 运算符的情况下创建 CoOrds 对象。如果将 struct 换成 class,程序将不会编译。
代码


 public struct CoOrds
{
 public int x, y;

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


 // Declare a struct object without "new."
class TestCoOrdsNoNew
{
 static void Main()
 {
 // Declare an object:
 CoOrds coords1;

 // Initialize:
 coords1.x = 10;
 coords1.y = 20;

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

 // Keep the console window open in debug mode.
 Console.WriteLine("Press any key to exit.");
 Console.ReadKey();
 }
}