在反序列化 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; }
}

如果在 json 中找不到设置默认属性值的无关但有用的链接:Default value for missing properties with JSON.net

,

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

https://sitename.com/contact.php

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

    set
    {
        _id = _id ?? value;
    }

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

,

我认为只使用私人二传手就可以了。只是不要再次调用它。 如果它们相同,您也可以省略属性名称。

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

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