gpt4 book ai didi

.net - 如何将派生类序列化为其基类

转载 作者:行者123 更新时间:2023-12-04 15:16:19 27 4
gpt4 key购买 nike

我有一个派生类,它只向基类添加方法。如何序列化派生类以使其与基类的序列化相匹配?
即派生类的序列化 xml 应如下所示:

<BaseClass>
...
</BaseClass>

例如
以下将抛出 InvalidOperationException

The type DerivedClass was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.


Class BaseClass {}

Class DerivedClass : BaseClass {}

DerivedClass derived = new DerivedClass();

StreamWriter stream = new StreamWriter("output file path");
XmlSerializer serializer = new XmlSerializer(GetType(BaseClass));
serializer(stream, derived);

最佳答案

您必须将 GetType(DerivedClass) 传递给序列化器构造函数,它必须与您序列化的对象的类型相匹配。您可以使用 <XmlRoot>属性重命名为根元素。此示例代码按预期工作:

using System;
using System.Xml.Serialization;
using System.IO;

class Program {
static void Main(string[] args) {
var obj = new DerivedClass();
obj.Prop = 42;
var xs = new XmlSerializer(typeof(DerivedClass));
var sw = new StringWriter();
xs.Serialize(sw, obj);
Console.WriteLine(sw.ToString());

var sr = new StringReader(sw.ToString());
var obj2 = (BaseClass)xs.Deserialize(sr);
Console.ReadLine();
}
}

public class BaseClass {
public int Prop { get; set; }
}
[XmlRoot("BaseClass")]
public class DerivedClass : BaseClass { }

关于.net - 如何将派生类序列化为其基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1824100/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com