gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:15:09 24 4
gpt4 key购买 nike

我有一个额外的便利构造函数的记录:

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)
{
}
}
我想从 JSON 对象反序列化它:
JsonConvert.DeserializeObject<PublishedTestMethod>(json);
我收到错误:

Unable to find a constructor to use for type Namespace.PublishedTestMethod. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.


理想情况下,我想分配 [JsonConstructor]归因于长构造函数,因为我认为这可以让它很好地从 JSON 映射。将它添加到记录本身不起作用,而且我看不到 attribute target对于构造函数。有没有办法做到这一点?

最佳答案

我不确定,你想要的在语法上是可能的。
我会做的是这样的:

public static class TestMethodExtensions
{
public static PublishedTestMethod ToRecord( this TestMethod tm )
{
PublishedTestMethod myRecord = new ( tm.Id,
tm.Name,
tm.Version,
tm.Status,
tm.Publisher,
tm.DatePublished);
return myRecord;
}
}
所以,你可以这样做
PublishedTestMethod ptm = myTestMethodInstance.ToRecord();

关于c# - 如何向记录的主构造函数添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68860104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com