C#内存管理(五)

本文通过示例展示了在C#中使用引用类型时,对象拷贝和不拷贝的区别,特别是针对嵌套引用类型如结构体的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么是这样的结果呢?我们来看一下程序过程:

如果我们没传递Thing对象的引用,那么我们将得到相反的结果。

拷贝和不拷贝

首先我们查看值类型,请使用下面的类和结构体。我们拥有一个Dude类包含个Name元素和2个Shoe。我们还有一个CopyDude()方法去产生一个新的Dude对象。

public struct Shoe {
  public string Color;
}
public class Dude {
  public string Name;
  public Shoe RightShoe;
  public Shoe LeftShoe;
  public Dude CopyDude () {
    Dude newPerson = new Dude();
    newPerson.Name = Name;
    newPerson.LeftShoe = LeftShoe;
    newPerson.RightShoe = RightShoe;
    return newPerson;
  }
  public override string ToString () {
    return (Name + " : Dude!, I have a " + RightShoe.Color +
      " shoe on my right foot, and a " +
       LeftShoe.Color + " on my left foot.");
  }
}

Dude类是一个引用类型并且因为Shoe结构是类的一个成员,所以它们都被分配到堆中。

运行下面的程序:

public static void Main () {
  Class1 pgm = new Class1();
  Dude Bill = new Dude();
  Bill.Name = "Bill";
  Bill.LeftShoe = new Shoe();
  Bill.RightShoe = new Shoe();
  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";
  Dude Ted = Bill.CopyDude();
  Ted.Name = "Ted";
  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";
  Console.WriteLine(Bill.ToString());
  Console.WriteLine(Ted.ToString());
}

我们将得到如下的输出:Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot.Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot.那么我们将Shoe声明为一个引用类型又会产生什么结果呢?

public class Shoe {
  public string Color;
}

再次运行main()函数, 我们得到的结果是:Bill : Dude!, I have a Red shoe on my right foot, and a Red on my left foot

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值