在反序列化 JsonProperty 时只允许设置 属性 的最佳方法?

Best way to only allow the setting of a property while deserializing a JsonProperty?

我想读入 id 但我不想在读入后设置它。_processing 变量是在读入文件和反序列化时设置的,因此可以设置它。有没有更优雅的内置方式来处理这个问题?

    private string _id;
    [JsonProperty(PropertyName = "id")]
    public string id
    {
        get { return _id; }
        set
        {
            if (_processing) // Only allow when reading the file
            {
                _id = value;
            }
        }
    }

如果您只能使用 init 属性(C#9.0 起)(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init):

[JsonProperty(PropertyName = "id")]
public string Id { get; init; }

如果没有...

private string _id;
[JsonProperty(PropertyName = "id")]
public string Id
{
    get { return _id; }
    set { _id ??= value; }
}

不相关但对设置默认 属性 值有帮助 link 如果在 json 中找不到它们:

在 C# 7.3 及更早版本中,您可以像这样使用空合并运算符:

    set
    {
        _id = _id ?? value;
    }

在 C# 8.0 及更高版本中,您可以执行以下操作:

    set
    {
        _id ??= value;
    }

??= 如果左侧操作数的计算结果为非空,则运算符不会计算其右侧操作数。

我认为只使用私有 setter 就可以了。只是不要再打电话了。 如果它们相同,您也可以省略 属性 名称。

    private string _id;
    [JsonProperty(PropertyName = "id")]
    public string id
    {
        get { return _id; }
        private set
        {
            _id = value;
        }
    }

    [JsonProperty]
    public string id { get; private set; }