gpt4 book ai didi

c# - 如何反序列化接口(interface)类型?

转载 作者:太空狗 更新时间:2023-10-29 22:56:10 25 4
gpt4 key购买 nike

我将一个包含名为 Model 的属性的类序列化为 IModel 但是当我尝试反序列化它时出现以下异常:

System.Runtime.Serialization.SerializationException: Type 'MYN.IModel' in Assembly 'MYN.Defs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

这是二进制序列化。 Model 标记为可序列化。显然 IModel 不是。

那么解决方案是什么,我做错了什么?为什么它无论如何都会尝试序列化或反序列化接口(interface)?

附言接口(interface)中没有枚举。

最佳答案

得到那个错误是有意义的,因为 IModel property 可以引用不同的类,并且不能保证它们都是可序列化的。


好的,我试了一下,我们有一个:

测试用例错误,它在我的电脑上运行。


interface IFoo { }

[Serializable]
class CFoo : IFoo { }

[Serializable]
class Bar
{
public IFoo Foo { get; set; }
}

Bar 可以很好地序列化和反序列化。

Bar b = new Bar();
b.Foo = new CFoo();

using (var s = new System.IO.MemoryStream())
{
var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(s, b);
s.Position = 0;
b = (Bar)bf.Deserialize(s);

Console.WriteLine("OK");
}

那么,与您的 IModel 有何不同?和 Model

关于c# - 如何反序列化接口(interface)类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1593414/

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