首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在KnownTypeAttribute上添加DataContractSerializer?

在KnownTypeAttribute上添加DataContractSerializer?
EN

Stack Overflow用户
提问于 2013-03-11 11:56:37
回答 2查看 1.9K关注 0票数 0

我在一个WebForms中,我试图将一个对象序列化成XML代码。那么,使用:

代码语言:javascript
复制
using (FileStream writer = new FileStream("c:/temp/file.xml", FileMode.Create, FileAccess.Write))
{
    DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType());
    ser.WriteObject(writer, videoContainer);
}

我得到了一个错误:键入'Google.GData.YouTube.YouTubeEntry‘,其数据契约名'YouTubeEntry:http://schemas.datacontract.org/2004/07/Google.GData.YouTube’是不需要的。向已知类型列表中添加任何静态不知道的类型--例如,使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。

所以我试了这个:

代码语言:javascript
复制
IEnumerable<string> lista = new List<string>();
lista.ToList().Add("YouTubeEntry:http://schemas.datacontract.org/2004/07/Google.GData.YouTube");

using (FileStream writer = new FileStream("c:/temp/file.xml", FileMode.Create, FileAccess.Write))
{
    DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType(), lista);
    ser.WriteObject(writer, videoContainer);
}

传递KnownTypeAttribute列表,但似乎无法得到一个列表?:O不确定我应该做什么.

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-11 12:01:43

您必须提供类型列表,而不是字符串列表。

代码语言:javascript
复制
var lista = new List<Type>();
lista.Add(typeof(Google.GData.YouTube.YouTubeEntry));

using (FileStream writer = new FileStream("c:/temp/file.xml", FileMode.Create, FileAccess.Write))
{
    DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType(), lista);
    ser.WriteObject(writer, videoContainer);
}
票数 2
EN

Stack Overflow用户

发布于 2013-03-11 12:02:58

应该将Type对象的集合传递给构造函数。不是弦乐。

代码语言:javascript
复制
DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType(), new List<Type> {typeof(YouTubeEntry)});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15337982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档