这是public static
类中的代码:
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异常?
_json = Json;
将再次调用getter,返回(旧的)后台字段值。所以你当前的代码类似于这样:
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);
}
}
Setter应该分配"value"变量,如
set {
json = value;
Console.Write...
}