我有一个在.NETFramework 4.6.1中运行的应用程序,它对抽象类和继承类型使用XML序列化,其方法与此XML序列化和继承类型几乎完全相同,而且效果很好。但是在将应用程序移植到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));引起异常
TestApp.CustomSerializer`1[TestApp.AnotherOne,System.InvalidOperationException: TestApp.AnotherOne,TestApp,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null不能被分配给TestApp,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null],TestApp,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null。
同样的代码也适用于.netframework应用程序。他们是在.netcore上改变了什么,还是我遗漏了什么?
发布于 2017-06-20 16:59:32
您的问题与表示序列化类型的类型链接。对于通用应用程序,它们必须来自(如我所见),例如:
[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
{
}使用通用序列化程序对您来说很重要吗?我已经测试过通用应用程序单元测试,并且所有的测试都是正确的。
附注:类型-从成员类型派生的对象的类型。从文件
发布于 2017-06-21 05:18:10
使用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;
}
}发布于 2018-03-20 18:13:13
尝试从Nuget下载System.Xml.XmlSerializer。我认为它是在.NETStandard这里开发的,列出所有版本的.NET标准和支持的平台
https://stackoverflow.com/questions/44545672
复制相似问题