【发布时间】:2023-03-11 17:00:01
【问题描述】:
我尝试使用 ToList 选项序列化字典的值。 我发现在反序列化过程中,我序列化的所有对象都为 null 当我使用内存流时没有发生这种情况,当我使用 .Net 对象作为字典中的类型时也没有发生。 下面是我创建的显示问题的示例代码 这段代码的输出是 字典:0-0 字典:1-1 列表:0 清单:1 字典:0-空 字典:1-空 列表:0
class Program
{
static void Main(string[] args)
{
A state = new A();
Stream stream = File.Open("D:\\temp\\temp.txt", FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, state);
stream.Close();
state.PrintData();
stream = File.Open("D:\\temp\\temp.txt", FileMode.Open);
bFormatter = new BinaryFormatter();
state = (A)bFormatter.Deserialize(stream);
stream.Close();
state.PrintData();
}
}
[Serializable()]
public class A : ISerializable
{
Dictionary<int, B> dic = new Dictionary<int, B>();
List<B> list = new List<B>();
public A()
{
for (int i = 0; i < 4; i++)
{
dic.Add(i, new B(i));
list.Add(new B(i));
}
}
public void PrintData()
{
foreach (KeyValuePair<int, B> kvp in dic)
{
Console.WriteLine("Dictionary: " + kvp.Key.ToString() + "-" + ((kvp.Value != null) ? kvp.Value.ToString() : "Null"));
}
foreach(B b in list)
{
Console.WriteLine("List: " + b.ToString());
}
}
public A(SerializationInfo info, StreamingContext context)
{
List<int> keys = info.GetValue("keys", typeof(List<int>)) as List<int>;
List<B> values = info.GetValue("values", typeof(List<B>)) as List<B>;
int count = keys.Count;
if(count == values.Count)
{
for(int i = 0; i < count; i++)
{
dic[keys[i]] = values[i];
}
}
list = info.GetValue("list", typeof(List<B>)) as List<B>;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("keys", dic.Keys.ToList(), typeof(List<int>));
info.AddValue("values", dic.Values.ToList(), typeof(List<B>));
List<B> listFromDic = new List<B>(dic.Values.ToList());
info.AddValue("list", listFromDic, typeof(List<B>));
}
}
[Serializable()]
public class B : ISerializable
{
int foo;
public B(int i)
{
foo = i;
}
public B(SerializationInfo info, StreamingContext context)
{
foo = info.GetInt32("foo");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("foo", foo);
}
public override string ToString()
{
return (foo != null) ? foo.ToString() : String.Empty;
}
}
【问题讨论】:
-
您为什么要尝试将字典序列化为列表?
Dictionary可直接序列化。 -
因为 .NET4 中的字典序列化已更改,支持旧序列化存在问题
-
嗨,Shimi,您想在问题中突出显示“.NET4 中的字典序列化已更改,支持旧序列化存在问题”。所以其他观众会知道这一点。我认为 .net 4 的前向兼容性优于 .net 2.0
-
嗨序列化的问题不是前向兼容性,而是向后兼容性,如果你在.Net4中序列化字典,你不能在以前的.Net中反序列化它,据我了解这是因为他们添加了内部比较器。解决方案也在我的代码中。但我不确定它为什么会发生,我认为这是因为 ToList 的输出不可序列化但我不确定
标签: c# generics serialization dictionary