123
public static string Serialize(object obj, Type[] extraTypes = null)
{
bool success = false;
Exception exception = null;
XmlSerializer sz = null;
string res = "";
StringWriter swr = null;
try
{
if (extraTypes == null)
{
sz = new XmlSerializer(obj.GetType());
}
else
{
sz = GetOrCreateSerializer(obj.GetType(), extraTypes);
}
swr = new StringWriter();
using (MemoryStream stream = new MemoryStream())
{
using (XmlWriter xtWriter = XmlWriter.Create(swr))
{
sz.Serialize(xtWriter, obj);
res = swr.ToString();
}
}
success = true;
}
catch (Exception ex)
{
success = false;
exception = ex;
}
finally
{
if (swr != null)
{
swr.Close();
swr.Dispose();
}
}
if (success)
{
return res;
}
else
{
throw exception;
}
}
private static Dictionary<string, XmlSerializer> _ComplexSerializers = new Dictionary<string, XmlSerializer>();
private static object _ComplexSerializersLockObj = new object();
internal static XmlSerializer GetOrCreateSerializer(Type type, Type[] extraTypes)
{
if (extraTypes != null && extraTypes.Length > 0)
{
string[] names = new string[extraTypes.Length + 1];
names[0] = type.Name;
for (int i = 0; i < extraTypes.Length; i++)
{
names[i + 1] = extraTypes[i].Name;
}
string key = string.Join(",", names);
if (!_ComplexSerializers.ContainsKey(key))
{
lock (_ComplexSerializersLockObj)
{
if (!_ComplexSerializers.ContainsKey(key))
{
XmlSerializer serializer = new XmlSerializer(type, extraTypes);
_ComplexSerializers.Add(key, serializer);
}
}
}
return _ComplexSerializers[key];
}
else
{
return new XmlSerializer(type);
}
}