1

I'm attempting to serialize (and subsequently deserialize) a rather simple class to an XML string, but am getting an exception: "The type System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] may not be used in this context."

The method I'm using to serialize is:

public string ToXml(TaskListFilterConfig config)
{
    Type[] extraTypes = { typeof(FilterConfig), typeof(SortConfig) };

    XmlSerializer serializer = new XmlSerializer(config.GetType(), extraTypes);

    using (StringWriter writer = new StringWriter())
    {
        serializer.Serialize(writer, config);

        return writer.ToString();
    }
}

The classes I'm attempting to serialize are:

[XmlRoot(ElementName = "TaskListFilterConfig", IsNullable = false)]
[XmlInclude(typeof(FilterConfig))]
[XmlInclude(typeof(SortConfig))]
public class TaskListFilterConfig
{
    [XmlArray("FilterConfigList")]
    [XmlArrayItem("FilterConfig")]
    public List<FilterConfig> FilterConfigList { get; set; }

    [XmlArray("SortConfigList")]
    [XmlArrayItem("SortConfig")]
    public List<SortConfig> SortConfigList { get; set; }

    public TaskListFilterConfig() 
    {
        FilterConfigList = new List<FilterConfig>();
        SortConfigList = new List<SortConfig>();
    }
}


[XmlType("FilterConfig")]
public class FilterConfig
{

    public OperandType Operand { get; set; }

    public int SelectedOperatorIndex { get; set; }

    public int SelectedColumnIndex { get; set; }

    public object RightOperand { get; set; }

    public FilterConfig() { }
}

[XmlType("SortConfig")]
public class SortConfig
{
    public Infragistics.Windows.Controls.SortStatus SortDirection { get; set; }

    public int ColumnSelectedIndex { get; set; }

    public SortConfig() { }
}
4

1 回答 1

0

您的 Class Model 和 Searalizable 数据是错误的。

请注意,这TaskListFilterConfig是与 不同的类型extraTypesextraTypes还有一些其他的模型数据。

如果你想序列化TaskListFilterConfig类和数据:使用下面的代码

public string ToXml(TaskListFilterConfig config)
{
    XmlSerializer serializer = new XmlSerializer(typeOf(TaskListFilterConfig));
    using (StringWriter writer = new StringWriter())
    {
        serializer.Serialize(writer, config);
        return writer.ToString();
    }
}

或者,如果您还想extraTypes传递相关的模型数据。

我知道这是一个很晚的答案。只是想确保问题已得到解答。也许它会帮助将来的人。:)

于 2014-11-21T07:13:20.663 回答