gpt4 book ai didi

C# 引用类型行为

转载 作者:太空宇宙 更新时间:2023-11-03 17:59:31 24 4
gpt4 key购买 nike

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

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();
}
}

*** 编辑 ******
这个的输出应该是什么,以及 TestClass() 的对象将在执行期间创建多少次。

最佳答案

输出应该是:

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

C# passes by value unless the ref keyword is used. For value types the value is copied. For reference types the value of the reference is copied.

The variable i is completely unrelated to testClass.i. I'll look at the simple case first, i is an int - a value type. When you call the method Another with i as an argument it is passed by value so modifying the value of i inside the method Another it does not change the value of the variable i in Method - it is equal to 200 all the time.

The value of variable testClass is also passed by value, but in this case because it is a reference type the value of the reference is passed and so the variable testClass in Another initially refers to the same object as the variable in Method. When you modify the value of testClass.i in Another it changes the object you created in Method so that it's member is set to 300.

Then this line creates a new and unrelated object:

testClass = new TestClass();

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

分配前: 分配后:

+-------------+ +-------------+ +--------------+ +---- ---------+
|方法 | |另一个 | |方法 | |另一个 |
|测试类 | |测试类 | |测试类 | |测试类 |
+-------------+ +-------------+ +--------------+ +---- ---------+
| | | |
| | | |
v | v v
+-----------+ | +-----------+ +------------+
|测试类 |<-----------+ |测试类 | |测试类 |
|我 = 300 | |我 = 300 | |我 = 100 |
+-----------+ +------------+ +------------+

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

关于C# 引用类型行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3842980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com