.net - 如何将 XMLSerializer 与包含 IList<T> 成员的 CaSTLe ActiveRecord 结合使用

标签 .net xml-serialization castle-activerecord generic-list

我正在尝试将 XMLSerializer 与城堡事件记录类一起使用,如下所示:

[ActiveRecord("Model")]
public class DataModel : ActiveRecordBase
{
    private IList<Document> documents;

    [XmlArray("Documents")]
    public virtual IList<Document> Documents
    {
        get { return documents; }
        set
        {
            documents = value;    
        }
    }
}

但是,XMLSerializer 由于 IList 接口(interface)而遇到了麻烦。 (引发异常:无法序列化“System.Collections.Generic.IList`1”类型的成员“DataModel.Documents”....)

我在其他地方读到这是 XMLSerializer 中的限制,建议的解决方法是将其声明为 List<T>而是接口(interface)。

因此我尝试更改 IList<Document>List<Document> 。 这会导致 ActiveRecord 引发异常: 属性 DataModel.Documents 的类型必须是接口(interface)(IList、ISet、IDictionary 或其通用对应部分)。您不能使用 ArrayList 或 List 作为属性类型。

所以,问题是:如何将 XMLSerializer 与包含 IList 成员的 CaSTLe ActiveRecord 一起使用?

最佳答案

有趣...我能建议的最好方法是在 Documents 上使用 [XmlIgnore] - ActiveRecord 是否有类似的忽略成员的方法?你可以这样做:

[XmlIgnore]
public virtual IList<Document> Documents
{
    get { return documents; }
    set
    {
        documents = value;    
    }
}

[Tell ActiveRecord to ignore this one...]
[XmlArray("Documents"), XmlArrayItem("Document")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public Document[] DocumentsSerialization {
    get {
         if(Documents==null) return null;
         return Documents.ToArray(); // LINQ; or do the long way
    }
    set {
         if(value == null) { Documents = null;}
         else { Documents = new List<Document>(value); }
    }
}

关于.net - 如何将 XMLSerializer 与包含 IList<T> 成员的 CaSTLe ActiveRecord 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/753099/

相关文章:

c# - 从 powershell ISE 调用时无法以异步 C# 代码写入控制台

c# - 异步/等待指导 : Intrinsic Signature Proliferation

c# - 异步和同步版本的方法

java - 如何正确使用 Jackson 的 JaxbAnnotationIntrospector?

.net - DataGridView、BindingList<T>、DataGridViewComboBoxColumn

c# - 如何将 2d30m 这样的字符串格式更改为时间跨度?

c# - 在保留原始 xml 的同时将 xml 序列化为对象?

c# - 反序列化具有未知元素顺序的 XML

activerecord - CaSTLe ActiveRecord 播种主键值

c# - 在 CaSTLe ActiveRecord 中尝试通过主键查找