我有一个运行.NETFramework 4.6.1的应用程序,对抽象类和继承类型使用xml序列化,其方法几乎与此XML Serialization and Inherited Types相同,并且效果很好。但在将应用程序移植到UWP .NETCore之后,我遇到了一个奇怪的异常。这是一个重现它的简单例子。
public class ClassToSerialize
{
[XmlElement(Type = typeof(CustomSerializer<AnotherOne>))]
public AnotherOne anotherOne;
public ClassToSerialize()
{
}
}
public abstract class AnotherOne
{
public AnotherOne()
{
}
}
public class CustomSerializer<TType> : IXmlSerializable
{
public CustomSerializer()
{
}
public CustomSerializer(TType data)
{
m_data = data;
}
public static implicit operator CustomSerializer<TType>(TType data)
{
return data == null ? null : new CustomSerializer<TType>(data);
}
public static implicit operator TType(CustomSerializer<TType> obj)
{
return obj.m_data;
}
private TType m_data;
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
}
public void WriteXml(XmlWriter writer)
{
}
}
为此类型创建XmlSerializer
XmlSerializer sr = new XmlSerializer(typeof(ClassToSerialize));
导致异常
System.InvalidOperationException:TestApp.AnotherOne,TestApp,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null不能从TestApp.CustomSerializer`1 [[TestApp.AnotherOne,TestApp,Version = 1.0.0.0,Culture]中分配= neutral,PublicKeyToken = null]],TestApp,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null。
相同的代码适用于.netframework应用。他们在.netcore中改变了什么,或者我错过了什么?
答案 0 :(得分:0)
您的问题与代表序列化类型的类型相关联。对于通用应用程序,它们必须来自(我可以看到) 例如:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
XmlSerializer sr = new XmlSerializer(typeof(ClassToSerialize));
var demo = new DemoChild();
var ser = new ClassToSerialize {anotherOne = demo};
var stream = new MemoryStream();
sr.Serialize(stream, ser);
}
}
public class ClassToSerialize
{
[XmlElement(Type = typeof(DemoChild))]
public AnotherOne anotherOne;
public ClassToSerialize()
{
}
}
public abstract class AnotherOne : IXmlSerializable
{
protected AnotherOne()
{
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
}
public void WriteXml(XmlWriter writer)
{
}
}
public class DemoChild: AnotherOne
{
}
使用通用序列化器对您来说很重要吗?我已经在通用应用单元测试中进行了测试,并且所有工作都正常。
P.S。 Type - 从成员类型派生的对象的类型。来自文档
答案 1 :(得分:0)
使用XAML序列化程序:
nuget> Install-Package Portable.Xaml
public class ClassToSerialize
{
public AnotherOne anotherOne { get; set; }
public ClassToSerialize()
{
}
}
public abstract class AnotherOne
{
public AnotherOne()
{
}
}
public class ContainerOne : AnotherOne
{
public uint placeholder = 0xdeadcafe;
}
public void Test()
{
ClassToSerialize obj = new ClassToSerialize();
obj.anotherOne = new ContainerOne();
//or FileStream..
using (MemoryStream ms = new MemoryStream())
{
Portable.Xaml.XamlServices.Save(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
ClassToSerialize obj2 = Portable.Xaml.XamlServices.Load(ms) as ClassToSerialize;
}
}
答案 2 :(得分:0)
尝试从Nuget下载System.Xml.XmlSerializer
。我认为它是在.NETStandard
中开发的
这里lists all versions of .NET Standard and the platforms supported