下面这段代码是 MSDN 中的例子:
// cs_ref.csusing System;public class MyClass { public static void TestRef(ref char i) { // The value of i will be changed in the calling method i = 'b'; } public static void TestNoRef(char i) { // The value of i will be unchanged in the calling method i = 'c'; } // This method passes a variable as a ref parameter; the value of the // variable is changed after control passes back to this method. // The same variable is passed as a value parameter; the value of the // variable is unchanged after control is passed back to this method. public static void Main() { char i = 'a'; // variable must be initialized TestRef(ref i); // the arg must be passed as ref Console.WriteLine(i); TestNoRef(i); Console.WriteLine(i); }}大家很容易看出输出结果是:
bb那么如果把这个例子做一些新的改动,将值类型(这里用的是 char)改成引用类型,程序运行又是什么效果呢?
// ----------------------------------------// MyClass definitionpublic class MyClass{ public int Value;} // ----------------------------------------// Tester methodspublic static void TestRef(ref MyClass m){ m.Value = 10;} public static void TestNoRef(MyClass m){ m.Value = 20;} public static void TestCreateRef(ref MyClass m){ m = new MyClass(); m.Value = 100;} public static void TestCreateNoRef(MyClass m){ m = new MyClass(); m.Value = 200;} public static void Main(){ MyClass m = new MyClass(); m.Value = 1; TestRef(ref m); Console.WriteLine(m.Value); TestNoRef(m); Console.WriteLine(m.Value); TestCreateRef(ref m); Console.WriteLine(m.Value); TestCreateNoRef(m); Console.WriteLine(m.Value);}大家能马上给出正确的答案么?如果能,那看来你对 ref 的用法了解得还是非常不错的。其实如果大家对 C++ 比较熟悉的话,把这段代码换成 C++ 的就好理解的多了。
// ----------------------------------------// MyClass definition#pragma once class MyClass{public: int Value;}; typedef MyClass* MyClassPtr; // ----------------------------------------// Tester methodsvoid TestRef(char* i){ *i = 'b';} void TestNoRef(char i){ i = 'c';} void TestRef(MyClassPtr* m){ (*m)->Value = 10;} void TestNoRef(MyClassPtr m){ m->Value = 20;} void TestCreateRef(MyClassPtr* m){ delete (*m); *m = new MyClass(); (*m)->Value = 100;} void TestCreateNoRef(MyClassPtr m){ m = new MyClass(); m->Value = 200;} int main(int argc, char* argv[]){ char c = 'a'; TestRef(&c); printf("%c\n", c); // output: b TestNoRef(c); printf("%c\n", c); // output: b MyClassPtr m = new MyClass; m->Value = 1; TestRef(&m); printf("%d\n", m->Value); TestNoRef(m); printf("%d\n", m->Value); TestCreateRef(&m); printf("%d\n", m->Value); TestCreateNoRef(m); printf("%d\n", m->Value); delete m; return 0;}这两段分别用 C# 和 C++ 实现的代码的输出结果都是一样的。后面用 MyClass 测试的输出结果是:
1020100100具体的原因相信经过大家的分析应该会很清楚的。另外如果大家有兴趣可以用 structs 再试试,也可以同时对 structs 在 C++ 和 C# 中的区别有进一步的认识。