C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# 结构与类 区别

浅析C#中结构与类的区别

作者:反骨仔(二五仔)

本文主要对C#结构与类的区别进行简要分析,文中举了实例,便于理解,具有很好的参考价值,需要的朋友一起来看下吧

一、

二、

三、代码例子

1.新建 PointClass.cs

namespace StructAndClass
{
 internal class PointClass
 {
 public PointClass(int x, int y)
 {
  X = x;
  Y = y;
 }
 public int X { get; set; }
 public int Y { get; set; }
 }
}

2.新建 PointStruct.cs

namespace StructAndClass
{
 internal struct PointStruct
 {
 public int X { get; set; }
 public int Y { get; set; }
 public PointStruct(int x, int y)
 {
  X = x;
  Y = y;
 }
 }
}

3.Program.cs

using System;
namespace StructAndClass
{
 internal class Program
 {
 private static void Main(string[] args)
 {
  Console.WriteLine("PointStruct =====");
  var pStruct = new PointStruct(10, 10);
  Console.WriteLine("初始值:x={0},y={1}", pStruct.X, pStruct.Y);
  ModifyPointStruct(pStruct);
  Console.WriteLine("调用 ModifyPointStruct() 后的值:x={0},y={1}", pStruct.X, pStruct.Y);
  Console.WriteLine();
  Console.WriteLine("PointClass =====");
  var pClass = new PointClass(10, 10);
  Console.WriteLine("初始值:x={0},y={1}", pClass.X, pClass.Y);
  ModifyPointClass(pClass);
  Console.WriteLine("调用 ModifyPointClass() 后的值:x={0},y={1}", pClass.X, pClass.Y);
  Console.Read();
 }
 private static void ModifyPointStruct(PointStruct point)
 {
  Console.WriteLine("调用方法:ModifyPointStruct");
  point.X = 20;
  point.Y = 20;
  Console.WriteLine("修改成的值:x={0}, y={1}", point.X, point.Y);
 }
 private static void ModifyPointClass(PointClass point)
 {
  Console.WriteLine("调用方法:ModifyPointClass");
  point.X = 20;
  point.Y = 20;
  Console.WriteLine("修改成的值:x={0}, y={1}", point.X, point.Y);
 }
 }
}

4.结果:

【解析】

ModifyPointStruct(PointStruct point) 调用时修改的只是结构副本,所以原来的结构并没有发生变化;  

ModifyPointClass(PointClass point) 调用时所修改的对象是原对象,因为参数传递过来的是一个引用地址,这地址指向原对象

四、总结

结构是值类型并在堆栈中传递,每次使用方法进行修改的都只是结构副本;

至于类,传递的是内存地址的引用,修改的就是初始值

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!

您可能感兴趣的文章:
阅读全文