C#温故而知新学习系列之面向对象编程—定义结构(二)

  定义结构

  结构与类相似,主要区别在于,类是存储在堆上的引用类型,而结构是存储在堆栈上的值类型,以及访问方式和一些特征(结构不支持继承)。

  在C#中使用struct关键字,一个名称,一对大括号来定义一个结构,也是使用new关键字声明实例。

  结构的语法格式

  struct MyStruct
     { 
          //结构主体
     }

  实例

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  namespace _2_struct
  {
        struct MyStruct
        {
            public void GetName()
            {
                Console.WriteLine("我的名字叫小甜甜");
                Console.ReadKey();
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                MyStruct mystruct = new MyStruct();
                mystruct.GetName();
            }
        }
  }

  运行效果

  我们可以看到在结构中调用方法,和在类中调用方法是一样的

  

原文地址:https://www.cnblogs.com/menglin2010/p/2319130.html