C# | get/set 变量总是返回 null

C# | get/set variable always returning null

这是public staticclass中的代码:

public static string _json { get; set; }

public static string Json
{
    get { return _json; }
    set { 
        _json = Json;
        Console.WriteLine("Json variable was modified. Now it's value is: " + _json);
    }
}

为什么设置Json = "{}";时会出现NullReference异常?

Setter 应该给变量赋“值”,例如

set {
    json = value;
    Console.Write...
}

_json = Json; 将再次调用 getter,其中 returns 支持字段的(旧)值。所以您当前的代码类似于:

public static string get_Json() => _json;
public void set_Json(string value) => 
{
    var newValue = get_Json(); // here _json just returns the old value
    // you don´t use the provided value here
    _json = newValue; 
}

您需要使用 value-关键字:

public static string Json
{
    get { return _json; }
    set { 
        _json = value;
        Console.WriteLine("Json variable was modified. Now it's value is: " + _json);
    }
}