C#内存管理(四)

这种方法就更有效的进行操作内存,其实我们并不需要拷贝这块内存。

当我们传递的是值类型的引用,那么程序修改这个引用的内容都会直接反映到这个值上。

传递引用类型

传递引用类型参数有点类似于前面的传递值类型的引用。

public class MyInt {
  public int MyValue;
}
public void Go() {
   MyInt x = new MyInt();
   x.MyValue = 2;
   DoSomething(x);
   Console.WriteLine(x.MyValue.ToString());
}
public void DoSomething(MyInt pValue) {
  pValue.MyValue = 12345;
}

这段代码做了如下工作:

1.开始调用go()方法让x变量进栈。

2.调用DoSomething()方法让参数pValue进栈

3.然后x值拷贝到pValue

这里有一个有趣的问题是,如果传递一个引用类型的引用又会发生什么呢?

如果我们有两类:

public class Thing {
}
public class Animal : Thing {
  public int Weight;
}
public class Vegetable : Thing {
  public int Length;
}

我们要执行go()的方法,如下:

public void Go () {
  Thing x = new Animal();
  Switcharoo(ref x);
  Console.WriteLine(
   "x is Animal  :  "
   + (x is Animal).ToString());
  Console.WriteLine(
    "x is Vegetable :  "
    + (x is Vegetable).ToString());
}
public void Switcharoo (ref Thing pValue) {
  pValue = new Vegetable();
}

X的输出结果:

x is Animal  :  Falsex is Vegetable :  True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值