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

问题描述

这是 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 应该给变量赋值,例如

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