gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:32:58 25 4
gpt4 key购买 nike

在对现有项目运行代码分析时,我遇到了消息不要公开通用列表集合属性应该是只读的。但是,此类用于读取/写入 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; }

}

读取 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);
}
}
}

最佳答案

怎么样:

/// <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>();
}
}

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

关于c# - 序列化集合并遵守代码分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18118829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com