gpt4 book ai didi

.net - 序列化同一个对象会产生不同的流吗?

转载 作者:行者123 更新时间:2023-12-04 17:26:47 26 4
gpt4 key购买 nike

序列化同一个对象可能会产生不同的流时是否有任何情况(假设 .NET 内置的格式化程序之一用于两个序列化)?

这在下面的讨论中出现 this post .声称这可能发生,但没有提供具体的解释,所以我想知道是否有人可以对这个问题有所了解?

最佳答案

正如我在那个 SO 问题的评论中所解释的那样,该问题是由字符串输出的优化引起的(至少是我发现的情况)。 看起来如果字符串是相同的引用,那么它将输出一次。

那么我们的示例代码所做的就是使用一个长字符串作为对象的属性并更改一个字符串的引用,然后进行序列化。然后再次将流反序列化回对象(这次因为字符串被插入,所以使用相同的引用),然后再次序列化。这次的流是较小 .

好的,这是证明代码:

[Serializable]
public class Proof
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
}

class Program
{
static void Main(string[] args)
{

const string LongString =
"A value that is going to change the world nad iasjdsioajdsadj sai sioadj sioadj siopajsa iopsja iosadio jsadiojasd ";

var proof = new Proof() {
S1 = LongString,
S2 = LongString,
S3 = LongString
};

proof.S2 = LongString.Substring(0, 10) + LongString.Substring(10); // just add up first 10 character with the rest.
//This just makes sure reference is not the same although values will be

Console.WriteLine(proof.S1 == proof.S2);
Console.WriteLine(proof.S1 == proof.S3);
Console.WriteLine(proof.S2 == proof.S3);
Console.WriteLine("So the values are all the same...");

BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bf.Serialize(stream, proof);
byte[] buffer = stream.ToArray();
Console.WriteLine("buffer length is " + buffer.Length); // outputs 449 on my machine
stream.Position = 0;
var deserProof = (Proof) bf.Deserialize(new MemoryStream(buffer));
deserProof.S1 = deserProof.S2;
deserProof.S3 = deserProof.S2;
MemoryStream stream2 = new MemoryStream();
new BinaryFormatter().Serialize(stream2, deserProof);

Console.WriteLine("buffer length now is " + stream2.ToArray().Length); // outputs 333 on my machine!!
Console.WriteLine("What? I cannot believe my eyes! Someone help me ........");

Console.Read();
}

关于.net - 序列化同一个对象会产生不同的流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7954275/

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