我的类中有用于序列化/反序列化的方法,使用与使用默认序列化程序生成的 XML 结构不同的 XML 结构。这些方法为我的类型创建了一个 XmlSerializer,但有一大堆覆盖。当这些方法被调用时,我猜内部.NET 仍然会生成一个序列化程序集,但我想在编译后生成这个程序集,所以它不会在运行时生成。如何为此自定义序列化生成序列化程序集?如果我对该类型使用 sgen.exe,它似乎只生成默认序列化程序。
特别是我需要生成序列化程序集的原因是我的代码是从 Internet Explorer 进程中调用的,该进程在保护模式下运行。如果 .net 运行时尝试生成序列化程序集,它会调用 csc.exe 并提示用户,询问是否允许运行此进程。我不希望用户被提示!所以需要在没有 csc.exe 的情况下完成所有序列化/反序列化。
我能想到的一种选择是捕获在运行时生成的 .cs,将其放入单独的程序集中,然后将其包含在我的产品中。除了有点恶心之外,这引发了如何在我的构建过程中自动生成该 .cs 的问题......
也许还值得一提:我的自定义 xml 序列化也序列化嵌套类,所以也许也会有自动生成的序列化器。我的自定义序列化主要是按照以下几行完成的——它将 XmlIgnore 添加到某些属性并从其他属性中删除 XmlIgnore。其中许多属性返回需要序列化的对象,其中一些实现 IXmlSerializable,一些使用默认序列化。
public void SerializeToCustomXml1(XmlWriter writer)
{
try
{
CustomXmlSerializer1.Serialize(writer, this);
}
catch (Exception)
{
}
}
/// <summary>
/// Static serializer so it's created just once. There's another one like this CustomXmlSerializer2 with a slightly different format again.
/// </summary>
private static XmlSerializer CustomXmlSerializer1
{
get
{
if (_customXmlSerializer == null)
{
XmlAttributes dontIgnore = new XmlAttributes();
dontIgnore.XmlIgnore = false;
XmlAttributes attributes;
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
// Include some fields in the XML that wouldn't be there otherwise.
overrides.Add(typeof (WebResource), "ID", dontIgnore);
overrides.Add(typeof (WebResource), "HasDestinationURLs", dontIgnore);
overrides.Add(typeof (Resource), "AccessDefindBy", dontIgnore);
attributes = new XmlAttributes();
attributes.XmlIgnore = false;
attributes.XmlElements.Add(new XmlElementAttribute("ActionID"));
overrides.Add(typeof(Action), "ID", attributes);
// Instead of serializing the Actions field we serialize CustomActionsXmlSerializer,
// which outputs different content in the XML
overrides.Add(typeof (WebResource), "Actions", ignore);
attributes = new XmlAttributes();
attributes.XmlIgnore = false;
attributes.XmlElements.Add(new XmlElementAttribute("Actions"));
overrides.Add(typeof (WebResource), "CustomActionsXmlSerializer", attributes);
// ... more of these overrides here ...
_customXmlSerializer1 = new XmlSerializer(typeof(WebResource), overrides);
}
return _customXmlSerializer1;
}
更新:哦,这个答案表明这是不可能的,因为如果您使用 XmlOverrides,XmlSerializer 甚至不会寻找预编译的程序集。该死。然后我想我最好的选择是生成序列化代码并将其包含在我的项目中并直接调用它而不是调用 XmlSerializer。关于如何巧妙地做到这一点的任何想法?