【问题标题】:Best way to only allow the setting of a property while deserializing a JsonProperty?在反序列化 JsonProperty 时只允许设置属性的最佳方法?
【发布时间】:2020-12-30 14:40:47
【问题描述】:

我想读入 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;
            }
        }
    }

【问题讨论】:

标签: c# json properties


【解决方案1】:

如果您只能使用初始化属性(自 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

【讨论】:

  • 非初始化设置器解决方案确实给调用者一种错觉,即 ID 可以设置为另一个值。您可以再次设置它,但不会发生任何事情。为了防止这种情况,您还可以抛出 InvalidOperationException。
  • 当然。由实施者决定
【解决方案2】:

在 C# 7.3 及更早版本中,您可以像这样使用 null-coalescing 运算符:

    set
    {
        _id = _id ?? value;
    }

在 C# 8.0 及更高版本中,您可以这样做:

    set
    {
        _id ??= value;
    }

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

【讨论】:

  • 但这确实给调用者一种错觉,即 ID 可以设置为另一个值。您可以再次设置它,但不会发生任何事情。为了防止这种情况,您还可以抛出 InvalidOperationException。
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2011-09-23
    • 1970-01-01
    相关资源
    最近更新 更多