Skip to main content
 首页 » 编程设计

c#之为什么这个反序列化会抛出 StackOverflow 异常

2024年02月20日20soundcode

当我尝试反序列化我的 FooContainer (List) 时抛出一个错误。请只看这段代码的最后一部分。

public interface IFoo 
{ 
    object Value { get; } 
} 
 
public abstract class Foo<T> : IFoo 
{ 
    [XmlElement("Value")] 
    public T Value { get; set; } 
    [XmlIgnore] 
    object IFoo.Value { get { return Value; } } 
} 
 
public class FooA : Foo<string> { } 
public class FooB : Foo<int> { } 
public class FooC : Foo<List<Double>> { } 
 
[XmlRoot("Foos")] 
public class FooContainer : List<IFoo>, IXmlSerializable 
{ 
    public XmlSchema GetSchema() 
    { 
        throw new NotImplementedException(); 
    } 
 
    public void ReadXml(XmlReader reader) 
    { 
        XmlSerializer serial = new XmlSerializer(typeof(FooContainer)); 
        serial.Deserialize(reader); 
    } 
 
    public void WriteXml(XmlWriter writer) 
    { 
        ForEach(x => 
            { 
                XmlSerializer serial = new XmlSerializer(x.GetType(), 
            new Type[] { typeof(FooA), typeof(FooB), typeof(FooC) }); 
                serial.Serialize(writer, x); 
            }); 
    } 
} 
 
class Program 
{ 
    static void Main(string[] args) 
    { 
        FooContainer fooList = new FooContainer() 
        { 
            new FooA() { Value = "String" }, 
            new FooB() { Value = 2 }, 
            new FooC() { Value = new List<double>() {2, 3.4 } }  
        }; 
 
        XmlSerializer serializer = new XmlSerializer(fooList.GetType(), 
            new Type[] { typeof(FooA), typeof(FooB), typeof(FooC) }); 
        System.IO.TextWriter textWriter = new System.IO.StreamWriter(@"C:\temp\movie.xml"); 
        serializer.Serialize(textWriter, fooList); 
        textWriter.Close(); 
 
        XmlReader reader = XmlReader.Create(@"C:\temp\movie.xml"); 
        var a = serializer.Deserialize(reader); 
    } 
} 

我做错了什么?

请您参考如下方法:

我有完全相同的问题:

在我看来,您的界面 IFoo 或类 Foo 中似乎缺少 set。如果没有 set,该对象将变为只读,当您尝试将 XML 反序列化为 Object 时,您将收到 StackOverflowException。

我只是将 set 添加到我的属性中,事情就自行解决了。