0

在阅读了很多似乎过时或似乎不太有效的代码后,我花了过去几个小时将以下代码放在一起。

如果它对这里的任何人有任何帮助,那就是最终的工作代码。如果可以改进,请免费评论:-)

public class SerializationHelper<T> {

#region static string SerializeObject( T obj, Encoding encoding )

/// <summary>
///   Serialize an [object] to an Xml String.
/// </summary>
/// <typeparam name="T">Object Type to Serialize</typeparam>
/// <param name="obj">Object Type to Serialize</param>
/// <param name="encoding">System.Text.Encoding Type</param>
/// <returns>Empty.String if Exception, XML string if successful</returns>
/// <example>
///   // UTF-16 Serialize
///   string xml = SerializationHelper<ObjectType>SerializeObject( [object], new UnicodeEncoding( false, false ) );
/// </example>
/// <example>
///   // UTF-8 Serialize
///   string xml = SerializationHelper<ObjectType>SerializeObject( [object], Encoding.UTF8 );
/// </example> 
public static string SerializeObject( T obj, Encoding encoding ) {

  if ( obj == null ) { return string.Empty; }

  try {

    XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) );

    using ( MemoryStream memoryStream = new MemoryStream() ) {

      XmlWriterSettings xmlWriterSettings = new XmlWriterSettings() { Encoding = encoding };

      using ( XmlWriter writer = XmlWriter.Create( memoryStream, xmlWriterSettings ) ) {

        xmlSerializer.Serialize( writer, obj );

      }

      return encoding.GetString( memoryStream.ToArray() );

    }

  }
  catch {

    return string.Empty;

  }

}

#endregion   

#region static T DeserializeObject( string xml, Encoding encoding )

/// <summary>
///   Deserialize an Xml String to an [object]
/// </summary>
/// <typeparam name="T">Object Type to Deserialize</typeparam>
/// <param name="xml">Xml String to Deserialize</param>
/// <param name="encoding">System.Text.Encoding Type</param>
/// <returns>Default if Exception, Deserialize object if successful</returns>
/// <example>
///   // UTF-16 Deserialize
///   [object] = SerializationHelper<ObjectType>DeserializeObject( xml, Encoding.Unicode )
/// </example>
/// <example>
///   // UTF-8 Deserialize
///   [object] = SerializationHelper<ObjectType>DeserializeObject( xml, Encoding.UTF8 )
/// </example> 
public static T DeserializeObject( string xml, Encoding encoding ) {

  if ( string.IsNullOrEmpty( xml ) ) { return default( T ); }

  try {

    XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) );

    using ( MemoryStream memoryStream = new MemoryStream( encoding.GetBytes( xml ) ) ) {

      // No settings need modifying here
      XmlReaderSettings  xmlReaderSettings  = new XmlReaderSettings();

      using ( XmlReader xmlReader = XmlReader.Create( memoryStream, xmlReaderSettings ) ) {

        return (T)xmlSerializer.Deserialize( xmlReader );

      }

    }

  }
  catch {

    return default( T );

  }

}

#endregion     

}
4

2 回答 2

0

我建议将类型参数移动T到封闭类并创建XmlSerializer实例static。泛型类中的静态字段是每个封闭类型,因此SerializationHelper<Apple>每个SerializationHelper<Orange>都有单独的字段实例。

另外,我也不确定这catch { return String.Empty; }是否是最好的主意——掩盖问题以避免崩溃让我感到紧张。

于 2011-02-17T05:27:30.433 回答
0

I think there is no need for the whole Encoding part. You simply serialise using one encoding, then convert to bytes, and then convert back to Unicode. Why is that? But I might be missing something here.

Another thing that hits me is .ToArray() usage. If you have big hiearchy and serialising lot of objects, this can be pretty performance heavy. Try using StreamReader to read the memory stream without need to copy it into to Array. But this requires some performance testing to back up my reasoning.

于 2011-02-17T06:43:24.927 回答