C#引用类型行为

Vij*_*dra 1 c# asp.net

我对引用类型有些困惑以下是测试示例请告诉我它是如何工作的

class TestClass
{
    public int i = 100;
}

class MyTestClass
{
    public void Method()
    {
        int i = 200;
        var testClass = new TestClass();
        testClass.i = 300;
        Another(testClass, i);
        Console.WriteLine("Method 1:" + testClass.i);
        Console.WriteLine("Method 2:" + i);
    }
    public void Another(TestClass testClass, int i)
    {
        i = 400;
        testClass.i = 500;
        testClass = new TestClass();
        //If we have set here again testClass.i = 600; what should be out putin this case
        Console.WriteLine("Another 1:" + testClass.i);
        Console.WriteLine("Another 2:" + i);
    }
    public static void Main()
    {
        MyTestClass test = new MyTestClass();
        test.Method();
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

*** EDIT ****** 应该是什么输出,以及TestClass()的Object在执行期间创建的次数.

Mar*_*ers 5

输出应该是:

Another 1:100
Another 2:400
Method 1:500
Method 2:200

除非使用ref关键字,否则C#按值传递.对于值类型,将复制该值.对于引用类型,将复制引用的.

变量i完全不相关testClass.i.我先看一下简单的情况,i是一个int - 一个值类型.当你调用该方法Anotheri作为参数,它是由值,修改的值传递i的方法内Another它不会改变变量的值iMethod-它等于200的所有时间.

变量的值testClass也通过值传递,但在这种情况下,因为它是引用类型,所以引用的值是传递的,因此变量最初引用与变量testClassin Another相同的对象Method.当您修改其中的值时testClass.i,Another更改您创建的对象,Method以便它的成员设置为300.

然后这一行创建一个新的无关对象:

testClass = new TestClass();
Run Code Online (Sandbox Code Playgroud)

有时更容易看到图中发生的情况,其中顶行显示变量,底行显示它们引用的对象:

Before assignment:                      After assignment:

+-------------+    +-------------+      +-------------+    +-------------+
| Method      |    | Another     |      | Method      |    | Another     |
| testClass   |    | testClass   |      | testClass   |    | testClass   |
+-------------+    +-------------+      +-------------+    +-------------+
       |                  |                    |                  |
       |                  |                    |                  |
       v                  |                    v                  v
 +-----------+            |              +-----------+      +-----------+
 | TestClass |<-----------+              | TestClass |      | TestClass |
 | i = 300   |                           | i = 300   |      | i = 100   |
 +-----------+                           +-----------+      +-----------+

因此,testClass.i打印时Another的值是构造函数中设置的默认值,即100.赋值不会修改原始对象.您只是将变量重新分配以指向其他内容.