public static string SerializeObject<T>(T obj)
{
try
{
string xmlString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlString = UTF8ByteArrayToString(memoryStream.ToArray()); return xmlString;
}
catch
{
return string.Empty;
}
}
这来自 - 链接
有没有办法在不需要重新分配内存流对象的情况下编写这个? 难道不应该将其丢弃(包装在 using 块中)吗?使用然后重新分配的内存流是什么?
我也不理解内存流重新分配。这是我的重构版本。
public static string SerializeObject<T>(T obj)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xwriter = new XmlTextWriter(ms, Encoding.UTF8);
xs.Serialize(xwriter, obj);
return UTF8ByteArrayToString(ms.ToArray());
}
}
catch
{
return string.Empty;
}
}
你是对的。您应该将流包装在 using 块中。并且在using块中使用变量时不允许重新赋值。甚至不需要进行序列化。你可以这样做:
public static string SerializeObject<T>(T obj)
{
try
{
string xmlString = null;
using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, obj);
xmlString = UTF8ByteArrayToString(memoryStream.ToArray());
return xmlString;
}
}
catch
{
return string.Empty;
}
}
我会以与其他答案略有不同的方式重构此代码,以首先检查类型是否可序列化。无法通过使用约束来做到这一点(http://bit.ly/c2Hq4s),但无论如何你都可以轻松检查它。我只是省略了 using 并添加了 Final 只是为了表明您也可以在不使用 using 的情况下完成它。
public static string SerializeObject<T>(T obj)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("type is not serializable");
}
string xmlString = string.Empty;
MemoryStream memoryStream = new MemoryStream();
try
{
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, obj);
xmlString = UTF8ByteArrayToString(memoryStream.ToArray());
}
catch // something useful here
{
// Do something useful here
}
finally
{
// Dispose of what you want here
}
return xmlString;
}
public static string SerializeObject<T>(T o)
{
string serializeObject = string.Empty;
if (o != null)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer xs = new XmlSerializer(typeof(T));
xs.Serialize(ms, o);
using (System.IO.StreamReader sr = new StreamReader(ms))
{
serializeObject = sr.CurrentEncoding.GetString(ms.ToArray());
}
}
}
catch { }
}
return serializeObject;
}