0

我正在尝试System.Text.Json与源生成一起使用。不幸的是,我有一个类有一个TimeSpan需要序列化的数据成员。但是,我无法让它与源生成一起使用,因为它总是尝试序列化私有数据成员_ticks。我不知道是否有办法禁用给定类型的源生成并改用用户提供的源生成。我什至试图忽略这些字段,但似乎没有考虑到:

[JsonSerializable(typeof(Test))]
partial class Context : JsonSerializerContext
{
}

public class Test
{
    public string Name { get; set; }

    [JsonIgnore]
    public TimeSpan Span { get; set; }
}

仍然给出以下错误:

'TimeSpan._ticks' 由于其保护级别而无法访问

你知道是否有解决方法吗?

这是生成错误的源生成部分: 这是 TimeSpan 序列化生成源的一部分,导致错误的部分,它是生成Context.TimeSpan.g.cs文件的一部分:

global::System.Text.Json.Serialization.Metadata.JsonPropertyInfoValues<global::System.Int64> info11 = new global::System.Text.Json.Serialization.Metadata.JsonPropertyInfoValues<global::System.Int64>()
{
    IsProperty = false,
    IsPublic = false,
    IsVirtual = false,
    DeclaringType = typeof(global::System.TimeSpan),
    PropertyTypeInfo = jsonContext.Int64,
    Converter = null,
    Getter = static (obj) => ((global::System.TimeSpan)obj)._ticks,
    Setter = static (obj, value) => global::System.Runtime.CompilerServices.Unsafe.Unbox<global::System.TimeSpan>(obj)._ticks = value!,
    IgnoreCondition = null,
    HasJsonInclude = false,
    IsExtensionData = false,
    NumberHandling = default,
    PropertyName = "_ticks",
    JsonPropertyName = null
};
4

1 回答 1

0

如果你注意到一些帮助,你应该发布真正的代码。您必须有一些使用 TimeSpan._ticks 的代码。尝试将其更改为 TimeSpan.Ticks。

于 2021-11-30T14:05:41.820 回答