【发布时间】:2012-03-18 00:37:33
【问题描述】:
在搜索了 99% 的网络后,我仍然卡在以下问题上。我有一个必须遵守合作伙伴公司提供的 wsdl 的 Web 服务。调用此服务的方法会产生一个(复杂的)类。不幸的是,调用服务时会引发序列化错误。
我已查明问题,但想不出(并找到)解决方案。因为我依赖于提供的 wsdl,所以我无法更改复杂的类结构。希望有人知道我错过了什么。这是重现我的问题的示例代码:
[System.SerializableAttribute()]
public class MyObject
{
public int Id { get; set; }
public object Item { get; set; } // <---- Note type *object* here
}
[System.SerializableAttribute()]
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
[TestClass]
public class SerializationTest
{
[TestMethod]
public void Serializing()
{
MyObject myObject = new MyObject { Id = 1 };
myObject.Item = new MyItem[] { new MyItem { Id = 1, Name = "Test" } };
string serializedString = SerializeObjectToXmlString(myObject, new []{ typeof(MyItem)});
Assert.IsFalse(String.IsNullOrWhiteSpace(serializedString));
}
/// <summary>
/// This method serializes objects to an XML string using the XmlSerializer
/// </summary>
private static string SerializeObjectToXmlString(object theObject, Type[] types)
{
using (var oStream = new System.IO.MemoryStream())
{
var oSerializer = new System.Xml.Serialization.XmlSerializer(theObject.GetType(), types);
oSerializer.Serialize(oStream, theObject); // <- Here the error is raised
return System.Text.Encoding.Default.GetString(oStream.ToArray());
}
}
}
在 Try/Catch 中,调用方法 Serialize() 后会引发错误。此错误的详细信息是:
InvalidOperationException was unhandled by user code
- There was an error generating the XML document.
The type MyItem[] may not be used in this context.
我的开发环境包括 Visual Studio 2010、.Net Framework 3.5。
编辑#1:添加序列化属性但错误仍然存在
【问题讨论】:
标签: c# visual-studio-2010 serialization .net-3.5