【问题标题】:How do I add an attribute to a record's primary constructor?如何将属性添加到记录的主构造函数?
【发布时间】:2021-08-20 09:37:07
【问题描述】:

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

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);

我得到错误:

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

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

【问题讨论】:

  • 我只是在 TestMethod 上创建一个扩展方法,它会创建记录。
  • 我已经把PublishedTestMethod(TestMethod tm)翻成了记录上的静态方法FromTestMethod,这样就避免了这个问题。尽管如此,我认为将它们都保留为构造函数并将第一个标记为用于 JSON 反序列化的构造函数会更优雅。

标签: c# record


【解决方案1】:

我不确定,你想要的在语法上是可能的。

我会做的是这样的:

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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2015-04-06
    • 2021-03-31
    • 2017-06-25
    • 2021-04-26
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多