gpt4 book ai didi

c# - C# 中集合的 XML 序列化

转载 作者:太空狗 更新时间:2023-10-29 21:48:03 24 4
gpt4 key购买 nike

我有两个类如下:

    public class Info
{
[XmlAttribute] public string language;
public int version;
public Book book;

public Info() { }

public Info(string l, int v, string author, int quantity, int price)
{
this.language = l;
this.version = v;
book = new Book(author, quantity, price);
}


}

public class Book
{
[XmlAttribute] public string author;
public int quantity;
public int price;
[XmlIgnore]public int total;
public NameValueCollection nvcollection = new NameValueCollection();

public Book() { }

public Book(string author, int quantity, int price)
{
this.author = author;
this.quantity = quantity;
this.price = price;
total = quantity * price;
nvcollection.Add(author, price.ToString());
}

}

我创建了一个 ArrayList,它添加了 Info 类的两个实例,如下所示:

            FileStream fs = new FileStream("SerializedInfo.XML", FileMode.Create);

List<Info> arrList = new List<Info>();

XmlSerializer xs = new XmlSerializer(typeof(List<Info>));

Info pObj = new Info("ABC", 3, "DEF", 2, 6);

Info pObj1 = new Info("GHI", 4, "JKL", 2, 8);

arrList.Add(pObj);
arrList.Add(pObj1);

xs.Serialize(fs, arrList);

fs.Close();

但是当我尝试序列化时,出现异常“反射(reflect)类型 'System.Collections.Generic.List`1[ConsoleApplicationSerialization.Info]' 时出现错误。”

我该如何调试?

此外,我可以使用哪种类型的结构来代替 namevaluecollection?

最佳答案

NameValueCollection does not directly implement the ICollection interface. Instead, NameValueCollection extends NameObjectCollectionBase. This implements the ICollection interface, and the overloaded Add(system.string) method is not implemented in the NameValueCollection class. When you use the XMLSerializer, the XmlSerializer tries to serialize or deserialize the NameValueCollection as a generic ICollection. Therefore, it looks for the default Add(System.String). In the absence of the Add(system.String) method, the exception is thrown.

尝试使用具有自定义序列化的容器类:

http://nayyeri.net/serialize-namevaluecollection

但是,我不确定您实际想要实现的目标是什么。一次 nvcollection 除了书的作者和价格,还会包含什么?

您打算在 Book 级别还是在对象层次结构的更高级别使用它?

您可能不使用 NameValueCollection,而是使用字典,因为它在包含的内容方面具有更大的灵 active :http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!699.entry

关于c# - C# 中集合的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1465054/

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