为什么引用类型不会在C#中更新

Gre*_*huk 2 c# static

这是我的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,为什么?

Rik*_*Rik 9

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).

  • 抱歉,我听不懂你在说什么。我绝不建议任何解决方法,因为我的代码正是OP的代码。如果您的问题是我的答案特定于OP的代码,而不是提供对引用是什么的更一般的解释,那么您是对的,但这就是OP所询问的。 (2认同)