c#结构体

定义结构

为了定义一个结构,您必须使用 struct 语句。struct 语句为程序定义了一个带有多个成员的新的数据类型。

在 C# 中,结构是值类型数据结构。它使得一个单一变量可以存储各种数据类型的相关数据。struct 关键字用于创建结构。

struct student
{
   public string name;
   public int xuehao;
   public double fenshu;
   
};  

C# 结构的特点

  • 结构可带有方法、字段、索引、属性、运算符方法和事件。
  • 结构可定义构造函数,但不能定义析构函数。但是,您不能为结构定义默认的构造函数。默认的构造函数是自动定义的,且不能被改变。
  • 与类不同,结构不能继承其他的结构或类。
  • 结构不能作为其他结构或类的基础结构。
  • 结构可实现一个或多个接口。
  • 结构成员不能指定为 abstract、virtual 或 protected。
  • 当您使用 New 操作符创建一个结构对象时,会调用适当的构造函数来创建结构。与类不同,结构可以不使用 New 操作符即可被实例化。
  • 如果不使用 New 操作符,只有在所有的字段都被初始化之后,字段才被赋值,对象才被使用。
  • 类 vs 结构

    类和结构有以下几个基本的不同点:

    • 类是引用类型,结构是值类型。
    • 结构不支持继承。
    • 结构不能声明默认的构造函数。
    • using System;
           
      struct student
      {
         private string name;
         private int xuehao;
         private double chengji;
        }
         public void getValues(string n, int x, double c)
         {
            name = t;
            xuehao=x;      
            chengji=c;
         }
         public void display()
         {
            Console.WriteLine("name : {0}", name);
            Console.WriteLine("xuehao : {0}", xuehao);
            Console.WriteLine("chengji : {0}", chengji);
           
         }
      
      };  
      
      public class student
      {
         public static void Main(string[] args)
         {
      
            student s= new student(); /* 声明s,类型为 student */
            student s2 = new student(); /* 声明s2,类型为 student */
      
            /* s1 详述 */
            s1.getValues("xuehao",
            "name", "chengji",+xuehao,name,chengji);
      
            /* s 2 详述 */
            s2.getValues("xuehao",
            "chengji", "name", +xuehao,name,chengji);
      
            /* 打印s1 信息 */
            s1.display();
      
            /* 打印 s2 信息 */
           s2.display(); 
      
            Console.ReadKey();
      
         }
      }
原文地址:https://www.cnblogs.com/yuyingming/p/5081692.html