如何向记录的主构造函数添加属性?

Chr*_*ley 11 c# record

我有一个带有附加便利构造函数的记录:

public record PublishedTestMethod(Guid Id, string Name, int Version, string Status, Guid? Publisher,
    DateTimeOffset? DatePublished)
{
    public PublishedTestMethod(TestMethod tm) : this(tm.Id, tm.Name, tm.Version, tm.Status, tm.Publisher,
        tm.DatePublished)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我想从 JSON 对象反序列化它:

JsonConvert.DeserializeObject<PublishedTestMethod>(json);
Run Code Online (Sandbox Code Playgroud)

我收到错误:

无法找到用于类型 Namespace.PublishedTestMethod 的构造函数。类应该具有默认构造函数、带参数的构造函数或标有 JsonConstructor 属性的构造函数。

理想情况下,我想将[JsonConstructor]属性分配给长构造函数,因为我认为这可以让它很好地从 JSON 映射。将其添加到记录本身不起作用,并且我看不到构造函数的属性目标。有没有办法做到这一点?

Ric*_*ide 2

要在记录或类的主构造函数上添加属性,您可以使用方法:target,如下所示:

[method: JsonConstructor]
public record PublishedTestMethod(Guid Id, string Name, int Version, string Status, Guid? Publisher,
    DateTimeOffset? DatePublished)
{
    public PublishedTestMethod(TestMethod tm) : this(tm.Id, tm.Name, tm.Version, tm.Status, tm.Publisher,
        tm.DatePublished)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

这是C# 12 中的新功能