序列化集合并遵守代码分析

Koe*_*oen 5 c# code-analysis xml-serialization .net-4.5

在现有项目上运行代码分析时,我遇到了消息不要公开通用列表集合属性应该是只读的。但是,此类用于从/向 xml 配置文件读取/写入。是否可以让这个类符合CA1002CA2227或者我是否必须禁止这些与 XML 相关的类的规则(项目中有很多)?

编辑

更改List<string>为已Collection<string>解决的 CA1002。仍然不知道如何解决 CA2227 并且仍然能够(反)序列化整个事情。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Serialization;

/// <summary>
/// Class containing the Configuration Storage
/// </summary>
[XmlRoot("Configuration")]
public class ConfigurationStorage
{
    /// <summary>
    /// Gets or sets the list of executers.
    /// </summary>
    [XmlArray("Executers")]
    [XmlArrayItem("Executer")]
    public Collection<string> Executers { get; set; }

    /// <summary>
    /// Gets or sets the list of IPG prefixes.
    /// </summary>
    [XmlArray("IpgPrefixes")]
    [XmlArrayItem("IpgPrefix")]
    public Collection<string> IpgPrefixes { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

读取xml文件:

    public static ConfigurationStorage LoadConfiguration()
    {
        if (File.Exists(ConfigFile))
        {
            try
            {
                using (TextReader r = new StreamReader(ConfigFile))
                {
                    var s = new XmlSerializer(typeof(ConfigurationStorage));
                    var config = (ConfigurationStorage)s.Deserialize(r);
                    return config;
                }
            }
            catch (InvalidOperationException invalidOperationException)
            {
                throw new StorageException(
                    "An error occurred while deserializing the configuration XML file.", invalidOperationException);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ond*_*dar 5

怎么样:

/// <summary>
/// Class containing the Configuration Storage
/// </summary>
[XmlRoot("Configuration")]
public class ConfigurationStorage {
  /// <summary>
  /// Gets or sets the list of executers.
  /// </summary>
  [XmlArray("Executers")]
  [XmlArrayItem("Executer")]
  public Collection<string> Executers { get; private set; }

  /// <summary>
  /// Gets or sets the list of IPG prefixes.
  /// </summary>
  [XmlArray("IpgPrefixes")]
  [XmlArrayItem("IpgPrefix")]
  public Collection<string> IpgPrefixes { get; private set; }

  public ConfigurationStorage() {
    Executers = new Collection<string>();
    IpgPrefixes = new Collection<string>();
  }
}
Run Code Online (Sandbox Code Playgroud)

这仍然适用于 xml 序列化/反序列化。