我已经完成了下面的代码,但是当我调试代码时,我发现像析构函数一样被调用了两次。r1,r2,r3,r4 应该被调用 4 次。我错过了什么。请帮助我,我是 c# 的新手。结构对象在什么时候被破坏。
using System;
struct Struct1
{
public int Value;
}
class Class1
{
public int Value = 0;
~Class1()
{
Console.WriteLine("Calling destructor");
}
}
class Test
{
static void Main()
{
Struct1 v1 = new Struct1();
Struct1 v2 = v1;
v2.Value = 123;
Class1 r1 = new Class1();
Class1 r2 = r1;
r2.Value = 123;
Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
Console.WriteLine("Refs: {0}, {1}", r1.Value, r2.Value);
vivek();
viku();
Console.ReadKey();
}
static void viku()
{
Struct1 v1 = new Struct1();
Struct1 v2 = v1;
v2.Value = 123;
Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
}
static void vivek()
{
Class1 r3 = new Class1();
Class1 r4 = r3;
r4.Value = 15;
// Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
Console.WriteLine("Refs: {0}, {1}", r3.Value, r4.Value);
Console.Write("Calling vivek");
}
}