字段是可序列化类型的成员,但属于不可序列化类型

Field is member of a type which is serializable but is of type which is not serializable

我正在使用 .NET Framework 4.7 开发 C# 库。

我想将 class ProductionOrderXmlFile 转换成 XML 文件:

[Serializable]
public class Level
{
    [XmlElement("Id")]
    public byte Id { get; set; }
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("CodeType")]
    public byte CodeType { get; set; }
    [XmlElement("CodeSourceType")]
    public byte CodeSourceType { get; set; }
    [XmlElement("HelperCodeType")]
    public byte HelperCodeType { get; set; }
    [XmlElement("HelperCodeSourceType")]
    public byte HelperCodeSourceType { get; set; }
    [XmlElement("PkgRatio")]
    public int PkgRatio { get; set; }
}

[Serializable]
public class VarData
{
    [XmlElement("VariableDataId")]
    public string VariableDataId { get; set; }
    [XmlElement("LevelId")]
    public byte LevelId { get; set; }
    [XmlElement("Value")]
    public string Value { get; set; }
}

/// <summary>
/// Class to load a production order from a xml file.
/// </summary>
[Serializable, XmlRoot("root")]
public class ProductionOrderXmlFile
{
    [XmlElement("ProductionOrderName")]
    public string ProductionOrderName { get; set; }
    [XmlElement("NumItems")]
    public int NumItems { get; set; }
    [XmlElement("ProductCode")]
    public string ProductCode { get; set; }
    [XmlElement("Reduction")]
    public float Reduction { get; set; }
    [XmlArray("Levels")]
    [XmlArrayItem("Level")]
    public List<Level> Levels { get; set; }
    [XmlArray("VariableDatas")]
    [XmlArrayItem("VariableData")]
    public List<VarData> VariableData { get; set; }
}

但在字段 public List<Level> Levels { get; set; }public List<VarData> VariableData { get; set; } 中我收到警告:

警告 CA2235 字段级别是可序列化的 ProductionOrderXmlFile 类型的成员,但属于不可序列化的 System.Collections.Generic.List 类型的成员

并且:

警告 CA2235 字段变量数据是可序列化的 ProductionOrderXmlFile 类型的成员,但属于不可序列化的 System.Collections.Generic.List 类型的成员

我需要做什么才能避免这些警告?

输了[Serializable]。把它扔掉 - 所有这些。 XmlSerializer不关心,也不需要。它对您没有帮助,并且会导致此误报警告。

[Serializable] 本质上 仅与 BinaryFormatter 相关,这通常不是一个好的选择。