Sonar Qube Error 更新“ISerializable”的实现以符合推荐的序列化模式

问题描述 投票:0回答:3

我目前正在开发 .net 4.6.2 应用程序。

我需要序列化一个 OData Api 调用,它工作得很好。

不幸的是,我遇到了 Sonar Qube 错误:

更新“ISerializable”的实现以符合推荐的序列化模式。

为了将我的 OData 导入到 C# 中,我使用以下类结构:

[Serializable]
public class Record : Dictionary<string, dynamic> { }

[DataContract]
public class Records
{
    [DataMember(Name = "@odata.context")]
    public string Context { get; set; }

    [DataMember(Name = "@odata.count")]
    public int Count { get; set; }

    [DataMember(Name = "value")]
    public IEnumerable<Record> Value { get; set; }
}

序列化工作正常,但我不知道如何解决这个 Sonar Qube 错误。

如何正确使用ISerializable和DataContract,真的可以吗?

你知道如何解决这个问题吗?

c# odata datacontract .net-4.6.2 iserializable
3个回答
1
投票

正如@Maritn Costello 所建议的

你可以像这样抑制这个警告。

#pragma warning disable S3925 // "ISerializable" should be implemented correctly
    public class Record : Dictionary<string, string> { }
#pragma warning restore S3925 // "ISerializable" should be implemented correctly

词典类工具

ISerializable

 public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, ISerializable, IDeserializationCallback
    {

0
投票

在我的例子中,我选择使用原生类型而不是自定义类。 它工作正常。

[DataMember(Name = "value")]
public List<Dictionary<string, dynamic>> Value { get; set; }

0
投票

您需要添加一个受保护的构造函数,其参数如下:

SerializationInfo info, StreamingContext context

所以有效代码是:

[Serializable]
public class Record : Dictionary<string, dynamic>
{
    protected Record(SerializationInfo info, StreamingContext context) : base(info, context)
    {

    }
}

[DataContract]
public class Records
{
    [DataMember(Name = "@odata.context")]
    public string Context { get; set; }

    [DataMember(Name = "@odata.count")]
    public int Count { get; set; }

    [DataMember(Name = "value")]
    public IEnumerable<Record> Value { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.