• Struct定义和使用


    类是引用类型,是保存在托管堆中的。通过定义类,我们可以在数据的生存期上得到很高的灵活性,但是也会让程序的性能有一定的损失。虽然这种损失很小,但当我们只需要定义一个很小的结构时,用类来定义就有些浪费,对于这样的问题,C#有相对应的方案来解决,那就是-结构(struct)

    结构(struct)是一种值类型。也就是说,结构实例是分配在线程堆栈上的,结构本身是包含有值的,而不是像类一样的引用类型,包含的是所指向堆当中的引用(指针)。也就是说,结构的生存周期与简单类型(int,double等)相同的。所以说我们在定义较小的类时,可以尽量使用结构。

    结构与类的区别:

    1)结构是值类型,不是引用类型。

    2)结构可以继承接口,但是不可以继承类或结构。

    3)结构的构造方法的工作方式有所不同,只能声明带参数的构造方法,且不能声明析构方法。

    4)可以指定字段如何在内存中布局。

    什么时候使用(struct)结构:

    虽然我们可以用(class)类完全代替(struct)结构,但是为了程序的性能的提高,建议大家在实现一个用于存储数据或数据量较小的结构时来使用结构,因为结构是值类型,所以在性能的影响上,是能起到正面作用的。

     

    MSDN中的定义:

    A struct type is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types.

     

    Example 1

    This example demonstrates struct initialization using both default and parameterized constructors.

    // keyword_struct.cs

    // struct declaration and initialization

    using System;

    public struct Point

    {

       public int x, y;

       public Point(int p1, int p2)

      {

          x = p1;

          y = p2;   

       }

    }

    class MainClass

    {

       public static void Main() 

       {

          // Initialize:  

          Point myPoint = new Point();

          Point yourPoint = new Point(10,10);

          // Display results:

          Console.Write("My Point:   ");

          Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);

          Console.Write("Your Point: ");

          Console.WriteLine("x = {0}, y = {1}", yourPoint.x, yourPoint.y);

       }

    }

    Output

    My Point:   x = 0, y = 0

    Your Point: x = 10, y = 10

    Example 2

    This example demonstrates a feature that is unique to structs. It creates a Point object without using the new operator. If you replace the word struct with the word class, the program won't compile.

    // keyword_struct2.cs

    // Declare a struct object without "new"

    using System;

    public struct Point

    {

       public int x, y;

       public Point(int x, int y)

       {

          this.x = x;

          this.y = y;

       }

    }

    class MainClass

    {

       public static void Main()

       {

          // Declare an object:

          Point myPoint;

          // Initialize:

          myPoint.x = 10;

          myPoint.y = 20;

          // Display results:

          Console.WriteLine("My Point:");

          Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);

       }

    }

    Output

    My Point:

    x = 10, y = 20

  • 相关阅读:
    前端JS的服务订阅&服务发布
    身份证号码校验解释
    基于密码强度检测算法分析及实现
    身份证号码的正则表达式
    如何安装 Sublime text 编辑器相关的插件
    关于GatewayClient 介绍和使用
    GatewayWorker与ThinkPHP等框架结合
    如何知道使用的GatewayWorker版本号?
    Hibernate HQL
    Hibernate 一对一
  • 原文地址:https://www.cnblogs.com/gsk99/p/1904554.html
Copyright © 2020-2023  润新知