c# - 如何将 XML 文件反序列化为具有只读属性的类?

标签 c# .net xml xml-serialization

我有一个类用作设置类,该类被序列化为 XML 文件,然后管理员可以编辑该文件以更改应用程序中的设置。 (这些设置比 App.config 允许的稍微复杂一些。)

我正在使用 XmlSerializer 类来反序列化 XML 文件,并且我希望它能够设置属性类,但我不希望其他开发人员使用该类/程序集能够通过代码设置/更改属性。我可以使用 XmlSerializer 类来实现这一点吗?

添加更多细节:这个特定的类是一个 Collection,根据 FxCop,XmlSerializer 类对反序列化只读集合有特殊支持,但我还没有找到任何有关它的更多信息。有关所违反规则的具体细节是:

Properties that return collections should be read-only so that users cannot entirely replace the backing store. Users can still modify the contents of the collection by calling relevant methods on the collection. Note that the XmlSerializer class has special support for deserializing read-only collections. See the XmlSerializer overview for more information.

这正是我想要的,但是如何做到呢?

编辑:好吧,我想我有点疯狂了。就我而言,我所要做的就是在构造函数中初始化 Collection 对象,然后删除属性 setter 。然后,XmlSerialized 对象实际上知道使用 Collection 对象中的 Add/AddRange 和索引器属性。以下内容确实有效!

public class MySettings
{
    private Collection<MySubSettings> _subSettings;
    public MySettings()
    {
       _subSettings = new Collection<MySubSettings>();
    }

    public Collection<MySubSettings> SubSettings
    {
         get { return _subSettings; }
    }
}

最佳答案

您必须使用可变列表类型,例如 ArrayList(或 IList IIRC)。

关于c# - 如何将 XML 文件反序列化为具有只读属性的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/133772/

相关文章:

iphone - 在 iPhone 中创建 Excel 支持的 XML

c# - PictureBox BackgroundImage 属性 C#

c# - 无需反射即可将 get/set 属性作为参数传递的最佳方法

c# - 使用 Unschedulejob 修改触发器详细信息 - 我做错了什么? ( quartz 网)

c# - 为 C# 生成的 XML 文档的 XSD?

javascript - 单击刷新 XML 提要 (jQTouch)

c# - 可以复制 Azure 存储文件共享吗?

.net - 需要在 .NET 应用程序中嵌入 Excel 工作表

c# - .NET 通过时区名称获取时区偏移量

java - 使用 JPA 和 Hibernate : Persistence. xml 进行 JUnit 测试