gpt4 book ai didi

c# - XmlSerializer 为 x86 和 x64 生成不同的输出

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:34 25 4
gpt4 key购买 nike

我有以下示例代码,它为 x86 和 x64 生成不同的输出。

class SampleSerializer
{
public static string Serialize(string[] samples)
{
var xmlDocument = string.Empty;

var xmlSerializer = new XmlSerializer(typeof(string[]));
using (var ms = new MemoryStream())
{
xmlSerializer.Serialize(
ms,
samples);

xmlDocument = Encoding.UTF8.GetString(ms.ToArray());
}

return xmlDocument;
}
}

class Program
{
static void Main(string[] args)
{
var samples = new string[] { };

var doc = SampleSerializer.Serialize(samples);

Console.WriteLine(doc);
}
}

当平台目标为 x86 时,输出为:

<?xml version="1.0"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

当平台目标为 x64 时,输出为:

<?xml version="1.0"?>
<ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />

您可以通过设置或取消设置 Any CPU 和 Prefer 32-bit 来实现相同的效果。

如果仔细观察,命名空间xsixsd 的顺序是不同的。为什么会这样?我希望命名空间的顺序与平台无关。

最佳答案

XmlSerializer 在内部使用 Hashtable 来保留命名空间( this one ,然后是 this one ),因此您可以将示例简化为以下内容:

var hash = new Hashtable();
hash.Add("xsi", null);
hash.Add("xsd", null);

foreach (var name in hash.Keys)
{
Console.WriteLine(name);
}

x86:

xsi
xsd

x64:

xsd
xsi

转载!根据MSDN,技术上这是预期的:

The order of the keys in the ICollection is unspecified

如果这还不够,我们可以在这里开始如履薄冰并猜测为什么会这样。我最好的猜测是 Keys 的顺序取决于 Keys 的哈希码。

好的,让我们试试:

Console.WriteLine("xsi: {0:x8}", "xsi".GetHashCode());
Console.WriteLine("xsd: {0:x8}", "xsd".GetHashCode());

x86:

xsi: c5864a25
xsd: c2b84cce

x64:

xsi: b9b66082
xsd: b9b66087

相同的字符串,不同平台的不同哈希码!

但这又是每 MSDN 所期望的:

The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across versions of the .NET Framework and across platforms (such as 32-bit and 64-bit) for a single version of the .NET Framework. In some cases, they can even differ by application domain.

呵呵呵,“它们甚至可以因应用领域而异”!

现在我不会依赖 XmlSerializer 总是产生稳定的结果..

关于c# - XmlSerializer 为 x86 和 x64 生成不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466524/

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