栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#中类与结构的区别实例分析

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#中类与结构的区别实例分析

类与结构是C#程序设计中基本的数据类型,而初学者往往不能很好的分清二者之间的区别。本文就以附带实例形式加以说明。具体如下:

一、基本概念:

类:引用类型,存储在堆中,栈中存储引用地址,在方法的传输中只是传输地址的引用,修改指向的对象会影响原有对象的值,传输中消耗内存小。

结构:值类型,存储在堆栈中,传输过程中传输整个对象的副本,修改指向对象的值不会影响原有的对象,传输中消耗内存大。

二、实例代码如下:

class Program
{
    static void Main(string[] args)
    {
      
      TestClass TC1 = new TestClass();
      TC1.x = 10;
      TC1.y = "10";
      Console.WriteLine("");
      Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y);
      TC1.x = 20;
      TC1.y = "20";
      Console.WriteLine("");
      Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y);

      
      Console.WriteLine("");
      TestClass TC2 = TC1;
      TC2.x = 10;
      TC2.y = "10";
      Console.WriteLine("");
      Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y);
      Console.WriteLine("TC2 x={0} y={0}", TC2.x, TC2.y);

      
      Console.WriteLine("");
      TestStruct TS1 = new TestStruct();
      TS1.x = 10;
      TS1.y = "10";
      Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y);
      Console.WriteLine("");
      TS1.x = 20;
      TS1.y = "20";
      Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y);
      
      Console.WriteLine("");
      TestStruct TS2 = TS1;
      TS2.x = 10;
      TS2.y = "10";
      Console.WriteLine("");
      Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y);
      Console.WriteLine("TS2 x={0} y={0}", TS2.x, TS2.y);

      Console.ReadLine();
    }
}
public class TestClass
{
  public int x;
  public string y;
}
public struct TestStruct
{
  public int x;
  public string y;
}

代码运行结果如下图所示:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/126205.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号