gpt4 book ai didi

.net - 使用 XmlAttributeOverrides 预编译 XmlSerializer

转载 作者:行者123 更新时间:2023-12-02 08:07:36 24 4
gpt4 key购买 nike

在 .NET 中构造 XmlSerializer 实例时,会动态生成用于序列化和反序列化指定类型的程序集。这是一个耗时的过程。 Microsoft 的 sgen.exe 工具可用于预编译 XmlSerializer 实例以便稍后使用它们,而无需动态生成它们。不幸的是,这对于使用 XmlAttributeOverrides 的 XmlSerializer 实例来说是不可能的。

有没有办法预编译这些 XmlSerializer 实例以避免在运行时生成?

最佳答案

Andreas,这不是 sgen 工具本身的问题,这是由于 XmlSerializer 实现造成的。

当您使用仅具有一个 Type 参数的构造函数创建 XmlSerializer 的实例时,它会检查缓存并查找预生成的程序集。但是,当您将构造函数与 XmlAttributeOverrides 一起使用时,XmlSerializer 不会检查任何缓存并立即生成临时程序集。

最有可能的是,这是因为您可以使用 XmlAttributeOverrides 参数实现序列化逻辑的彻底改变,而 sgen 等工具无法在编译时“预见”这种变化。

如果您需要预编译一些东西,您[叹气]必须避免 XmlAttributeOverrides。如果这不可能,请尝试提前创建所需的 XmlSerializer 实例(可能在后台线程中)。

仅供您引用,这里是默认构造函数的代码(检查缓存并尝试查找预生成的程序集):

public XmlSerializer(Type type, string defaultNamespace)
{
this.events = new XmlDeserializationEvents();
if (type == null)
{
throw new ArgumentNullException("type");
}
this.mapping = GetKnownMapping(type, defaultNamespace);
if (this.mapping != null)
{
this.primitiveType = type;
}
else
{
this.tempAssembly = cache[defaultNamespace, type];
if (this.tempAssembly == null)
{
lock (cache)
{
this.tempAssembly = cache[defaultNamespace, type];
if (this.tempAssembly == null)
{
XmlSerializerImplementation implementation;
Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out implementation);
if (assembly == null)
{
this.mapping = new XmlReflectionImporter(defaultNamespace).ImportTypeMapping(type, null, defaultNamespace);
this.tempAssembly = GenerateTempAssembly(this.mapping, type, defaultNamespace);
}
else
{
this.mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
this.tempAssembly = new TempAssembly(new XmlMapping[] { this.mapping }, assembly, implementation);
}
}
cache.Add(defaultNamespace, type, this.tempAssembly);
}
}
if (this.mapping == null)
{
this.mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
}
}

这是与 XmlAttributeOverrides 一起使用的构造函数(始终生成序列化程序集):

public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location, Evidence evidence)
{
this.events = new XmlDeserializationEvents();
if (type == null)
{
throw new ArgumentNullException("type");
}
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
for (int i = 0; i < extraTypes.Length; i++)
{
importer.IncludeType(extraTypes[i]);
}
this.mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
if (location != null)
{
this.DemandForUserLocation();
}
this.tempAssembly = GenerateTempAssembly(this.mapping, type, defaultNamespace, location, evidence);
}

关于.net - 使用 XmlAttributeOverrides 预编译 XmlSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/678676/

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