【问题标题】:Adding KnownTypeAttribute on DataContractSerializer?在 DataContractSerializer 上添加 KnownTypeAttribute?
【发布时间】:2013-03-11 11:56:37
【问题描述】:

我在一个 WebForms 中,我尝试将一个对象序列化为 XML 代码。好吧,使用:

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

我收到此错误:不应使用数据合同名称“YouTubeEntry:http://schemas.datacontract.org/2004/07/Google.GData.YouTube”键入“Google.GData.YouTube.YouTubeEntry”。将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给 DataContractSerializer 的已知类型列表中。

所以我尝试了这个:

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 不知道我应该怎么做...

【问题讨论】:

    标签: c# .net serialization


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

    • 不能直接做 lista.Add() 。 .NET 说它不包含“添加”的定义? :O
    【解决方案2】:

    您应该将 Type 对象的集合传递给构造函数。不是字符串。

    DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType(), new List<Type> {typeof(YouTubeEntry)});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多