这种方法就更有效的进行操作内存,其实我们并不需要拷贝这块内存。
当我们传递的是值类型的引用,那么程序修改这个引用的内容都会直接反映到这个值上。
传递引用类型
传递引用类型参数有点类似于前面的传递值类型的引用。
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