C#结构体基础

2019-08-08  本文已影响0人  86a262e62b0b

参考转载文档:
https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/structs

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/using-structs

注意

1. 结构体特点:

解释:与类不同,可以对结构进行实例化,而无需使用 new 运算符。 在这种情况下,没有调用任何构造函数,从而提高了分配效率。 但是,字段将保持为未分配状态且必须在在初始化所有字段之后才可使用对象。 这包括无法通过属性获取或设置值。如果使用默认的无参数构造函数实例化结构对象,则根据成员的默认值分配所有成员。这也解释了上面三点。

此示例同时使用了默认构造函数和参数构造函数来演示 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.
        var coords1 = new Coords();
        var coords2 = new Coords(10, 10);

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

        Console.Write("Coords 2: ");
        Console.WriteLine($"x = {coords2.x}, y = {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
*/

此示例演示了一个特定于结构的功能。 此功能可以创建 Coords 对象,而无需使用 new 运算符。 如果将 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 = {coords1.x}, y = {coords1.y}");

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

2. 结构体和类的选择:

上一篇 下一篇

猜你喜欢

热点阅读