这是我的c#代码.为什么引用类型不在C#中更新,下面是代码
class Program
{
public static void Main(string[] args)
{
var a = A.field;
A.field = "2";
Console.WriteLine(a);
Console.Read();
}
}
public static class A
{
public static string field = "1";
}
Run Code Online (Sandbox Code Playgroud)
结果是1,为什么?
public static void Main(string[] args)
{
var a = A.field; // `a` is now a reference to the string "1"
A.field = "2"; // `A.field` is now a reference to the string "2"
Console.WriteLine(a); // nothing else has changed, so `a` is still a reference to the string "1"
Console.Read();
}
Run Code Online (Sandbox Code Playgroud)
因此,您的问题的答案基本上是:引用不会更新,因为您没有更改要写入Console(a)的引用,而是更改另一个引用(A.field).