相关疑难解决方法(0)

如何定位记录类的属性?

定义记录类时,如何将属性定位到参数、字段或属性?

例如,我想使用,JsonIgnore但这不能编译,因为它对字段或属性有属性使用限制:

record Person(string FirstName, string LastName, [JsonIgnore] int Age);
Run Code Online (Sandbox Code Playgroud)

c# oop attributes c#-9.0 record-classes

15
推荐指数
2
解决办法
759
查看次数

构造函数中 C# 记录上的 JsonProperty

使用 C# 9 中的新 C# 记录类型,我想知道是否可以(用于序列化)JsonPropertyAttribute在构造函数参数上设置from Newtonsoft.Json。它似乎不是开箱即用的。

MWE:

using System;
using Newtonsoft.Json;

Console.WriteLine(JsonConvert.SerializeObject(new Something("something")));

record Something([JsonProperty("hello")] string world) {}
Run Code Online (Sandbox Code Playgroud)

输出:

{"world":"something"}
Run Code Online (Sandbox Code Playgroud)

预期输出:

{"hello":"something"}
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以让它像这样工作?还是我们必须使用真正的构造函数恢复到属性样式?

internal record Something
{
    public Something(string world) { World = world; }

    [JsonProperty("hello")] public string World { get; }
}
Run Code Online (Sandbox Code Playgroud)

.net c# json.net c#-9.0

4
推荐指数
1
解决办法
934
查看次数

标签 统计

c# ×2

c#-9.0 ×2

.net ×1

attributes ×1

json.net ×1

oop ×1

record-classes ×1