gpt4 book ai didi

c# - XmlSerializer.Serialize 异常 : "The type [type] was not expected."

转载 作者:太空宇宙 更新时间:2023-11-03 10:56:00 25 4
gpt4 key购买 nike

我正在尝试序列化这个类:

[XmlRoot("ArrayOfEvent")]
public class EventList
{
public EventList()
{

}

public EventList(IEnumerable<Event> items)
{
Items = items;
}

[XmlArray("")]
public IEnumerable<Event> Items { get; set; }
}

这是 EventList.Items 中包含的 Event 类:

public class Event
{
[XmlElement]
public string ID { get; set; }

[XmlElement]
public string Title { get; set; }

[XmlElement]
public string Description { get; set; }

[XmlElement]
public string Location { get; set; }

[XmlElement]
public DateTime? StartTime { get; set; }

[XmlElement]
public DateTime? EndTime { get; set; }

[XmlElement]
public bool? AllDay { get; set; }
}

这里是错误发生的地方:

public static XmlDocument ToXmlDocument<T>(T obj)
{
var xmlDocument = new XmlDocument();
var nav = xmlDocument.CreateNavigator();

if (nav != null)
{
using (var writer = nav.AppendChild())
{
var ser = new XmlSerializer(typeof(T));
ser.Serialize(writer, obj); //throws exception
}
}

return xmlDocument;
}

XmlSerializer 在调用 Serialize() 时给我这个错误:

The type Domain.EventList was not expected. 
Use the XmlInclude or SoapInclude attribute to specify types that are not
known statically.

我已经尝试在 EventList 类和 Event 类上使用 [XmlInclude(typeof(EventList))] 但都没有这些想法的工作。我不确定还能做什么。

有人熟悉这个问题吗?我该如何解决?提前致谢。

最佳答案

基本上,列表对于 XmlSerializer 来说有点特殊。如果您将 DTO 声明为具有具体列表类型,您将获得更多成功,例如:

[XmlArray("")]
public List<Event> Items { get; set; }

关于c# - XmlSerializer.Serialize 异常 : "The type [type] was not expected.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19502118/

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