【发布时间】:2013-08-08 05:55:25
【问题描述】:
在现有项目上运行代码分析时,我遇到了消息不要公开通用列表和集合属性应该是只读的。 但是,该类用于读取/写入 xml 配置文件。 是否有可能使这个类符合CA1002 和CA2227 或者我必须为 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; }
}
读取 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);
}
}
}
【问题讨论】:
-
暴露
Collection<T>而不是List<T>侧步警告但会使您的代码更臭。警告是告诉你公开IList<T>、ICollection<T>或者IEnumerable<T>而不是List<T>。但是,正如您所注意到的,标准XMLSerializer不是很灵活。我更喜欢没有using System.Collections.ObjectModel;的代码,Collection是您在该命名空间中使用的唯一类型。 -
@Jodrell 我同意,但我的手在这里有点束缚。现在至少我的老板很高兴,因为警告消失了;-)
标签: c# xml-serialization .net-4.5 code-analysis