使用xmlSerializer.Serialize和IEnumerable对象序列化对象 [英] Serialize Objects using xmlSerializer.Serialize and IEnumerable objects

查看:210
本文介绍了使用xmlSerializer.Serialize和IEnumerable对象序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,其中包含一个被定义为IEnumerable的对象,即

I have an object that holds an object that is definded as IEnumerable, i.e.

[Serializable]
[XmlRoot("MyObject")]
public class MyObject
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlArrayAttribute("Numbers")]
    public IEnumerable<string> Numbers { get; set; }
}

当我对对象运行XmlSerializer.Serialize时,即

When I run the XmlSerializer.Serialize against the object, i.e.

        MyObject myObject = new MyObject() { 
            Name = "My Name" ,
            Numbers= new List<string>(){"One", "Two"}
        };



     var xmlSerializer = XmlSerializer.FromTypes(new[] 
{ typeof(MyObject) })[0];
            using (var xmlWriter = XmlWriter.Create(@"MyObject.xml"))
            {
                if (xmlWriter != null) xmlSerializer.Serialize(xmlWriter, myObject);
            }

我得到


无法序列化成员
SerializeObjects.MyObject.Numbers
类型
System.Collections.Generic.IEnumerable`1 [[System.String,
mscorlib,Version = 2.0.0.0,
Culture = neutral,
PublicKeyToken = b77a5c561934e089]]
因为它是一个接口。

"Cannot serialize member SerializeObjects.MyObject.Numbers of type System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] because it is an interface."

据我所知,您无法序列化界面。

Which I understand that you can't serialize an interface.

现在提问:

公共IEnumerable Numbers {get; set;}的最佳声明是什么?

What is the best declaration for the "public IEnumerable Numbers { get; set; }"?

我应该使用 List< ;> ,如果不是为什么不呢?

Should I use List<>, if not why not?

推荐答案

一般而言,你应该使用 Collection< T> 如果您打算让您的班级用户可以自由修改它,或者 ReadOnlyCollection< T> 如果你这样做不。建议不要在公共接口中使用 List< T> 来源)。

In general terms, you should use Collection<T> if you intend users of your class to be free to modify it, or ReadOnlyCollection<T> if you do not. It is not recommended to use List<T> in public interfaces (source).

但是,由于此类用于XML序列化,因此可能不会将XML用作对象模型以外的任何其他目的,规则实际上并不像'普通'API那样适用,因为它除了 XmlSerializer 之外没有任何其他消费者,因此它并不重要你用的很多。我可能仍然坚持这些建议。

However, as this class is for XML Serialization and thus presumably isn't used for any purpose other than representing XML as an object model, the rules don't really apply in the same way as a 'normal' API because it will have no consumers other than the XmlSerializer, and so it doesn't really matter that much what you use. I'd probably still stick to the recommendations though.

这篇关于使用xmlSerializer.Serialize和IEnumerable对象序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆