看看下面的代码,告诉我为什么在调用函数 UpdateContext 后,变量 connection2 没有与变量 connection1 相同的哈希码。
当我将变量 connection2 设置为 connection1 时,两个变量都有一个指向相同内存地址的指针。但是在使用'new'指令修改指针的函数UpdateContext中通过ref传递变量connection1之后,connection1有一个新的指针地址,但connection2仍然是旧地址。
class Program
{
static void Main(string[] args)
{
var connectionInitializer = new ConnectionInitializer();
connectionInitializer.Initialize();
Console.ReadLine();
}
}
public class Connection
{
}
public class ConnectionInitializer
{
public void Initialize()
{
var connection1 = new Connection();
var connection2 = connection1;
Console.WriteLine("Connection 1 (Before ref): " + connection1.GetHashCode());
Console.WriteLine("Connection 2 (Before ref): " + connection2.GetHashCode());
this.UpdateContext(ref connection1);
Console.WriteLine("Connection 1 (After ref): " + connection1.GetHashCode());
Console.WriteLine("Connection 2 (After ref): " + connection2.GetHashCode());
}
private void UpdateContext(ref Connection connection)
{
connection = new Connection();
}
}
感谢您的帮助。