我有一堆类型化的 xmlserialize 对象:
class Serializer{
static XmlSerializer serializerRequest_EnterVehicle = new XmlSerializer(typeof(Request_EnterVehicle));
static XmlSerializer serializerRequest_Cancel = new XmlSerializer(typeof(Request_Cancel));
static XmlSerializer serializerRequest_PrintInfo = new XmlSerializer(typeof(Request_PrintInfo));
public string ObjToXML(object toSerialize)...
}
我不想在运行时创建这些,而是想让它们在应用程序启动时初始化这些是 Serializer 类的一部分,我不确定这是一个好方法吗?有没有更好的方法来进行这种初始化,还有其他相关的成本吗?
我是否正确假设此初始化成本仅通过使用 static 关键字完成一次?
编辑:该项目是一个适用于 windows mobile 6.1 Pro 设备的 .NET 3.5 Compact Framework 项目。
更新:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace SmartDevice_Proxy
{
public sealed class TypedXMLSerializers
{
private static volatile TypedXMLSerializers instance;
private static object syncRoot = new Object();
//Implementation as Singleton
static XmlSerializer serializerRequest_EnterVehicle = new XmlSerializer(typeof(Request_EnterVehicle));
static XmlSerializer serializerRequest_Cancel = new XmlSerializer(typeof(Request_Cancel));
static XmlSerializer serializerRequest_PrintInfo = new XmlSerializer(typeof(Request_PrintInfo));
private TypedXMLSerializers() { }
public static TypedXMLSerializers Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new TypedXMLSerializers();
}
}
return instance;
}
}
}
}
需要对此进行测试以确保线程安全。