【发布时间】:2017-01-26 18:28:02
【问题描述】:
我想将我的字典数据转换成 XML。我正在尝试使用 XML 序列化,但出现错误。下面是我的代码。
class Program
{
static void Main(string[] args)
{
Dictionary<int, AddressDetails> objDic = new Dictionary<int, AddressDetails>();
for (int i = 1; i <= 5; i++)
{
AddressDetails obj = new AddressDetails();
obj.HouseNo = i;
obj.StreetName = "New Street One " + i;
obj.City = "New Delhi One " + i;
objDic.Add(i, obj);
}
string str = Utility.GetXMLFromObject(objDic);
}
}
public class AddressDetails
{
public int HouseNo { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
private string PoAddress { get; set; }
}
public static class Utility
{
public static string GetXMLFromObject(object o)
{
StringWriter sw = new StringWriter();
XmlTextWriter tw = null;
try
{
XmlSerializer serializer = new XmlSerializer(o.GetType());
tw = new XmlTextWriter(sw);
serializer.Serialize(tw, o);
}
catch (Exception ex)
{
//Handle Exception Code
}
finally
{
sw.Close();
if (tw != null)
{
tw.Close();
}
}
return sw.ToString();
}
}
错误代码行:XmlSerializer serializer = new XmlSerializer(o.GetType());
错误描述:
类型 System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ConsoleApplication5.AddressDetails, ConsoleApplication5, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] 不受支持,因为它实现了 IDictionary。
请提出建议。
【问题讨论】:
标签: c# generics dictionary serialization