【问题标题】:C# generic serialization utility classC# 通用序列化实用程序类
【发布时间】:2011-03-18 13:05:57
【问题描述】:

我有一个现有的类,用于将对象序列化和反序列化到 XML 或从 XML 序列化对象。它是一个具有单个类型参数T 的泛型类,其唯一的约束是where T : IXmlSerializable。但是,我希望仍然能够在未实现 IXmlSerializable 但具有 [Serializable] 属性的类上使用此类。我该怎么做呢?

来自我的通用类:

public static class XmlSerializationUtils<T> where T : IXmlSerializable
{
    public static T DeserializeXml(XmlDocument xml) { ... }
    public static XmlDocument SerializeToXml(T toSerialize) { ... }
}

我找到了this discussion,但没有给出解决方案,只是我做不到where T : Serializable。尝试执行 where T : SerializableAttribute 会使 Visual Studio 说“不能使用密封类 'System.SerializableAttribute' 作为类型参数约束”。

编辑:基于Stephen's answer,我删除了XmlSerializationUtils&lt;T&gt; 的约束并添加了这个静态构造函数:

static XmlSerializationUtils()
{
    Type type = typeof(T);
    bool hasAttribute = null != Attribute.GetCustomAttribute(type,
        typeof(SerializableAttribute));
    bool implementsInterface =
        null != type.GetInterface(typeof(IXmlSerializable).FullName);
    if (!hasAttribute && !implementsInterface)
    {
        throw new ArgumentException(
            "Cannot use XmlSerializationUtils on class " + type.Name +
            " because it does not have the Serializable attribute " +
            " and it does not implement IXmlSerializable"
        );
    }
}

【问题讨论】:

    标签: c# generics xml-serialization constraints


    【解决方案1】:

    您可以使用对象类型的IsSerializable 属性来检查一个类型是否可序列化。

    myObj.GetType().IsSerializable
    

    如上所述,这不可能作为通用约束添加,但很可能会在构造函数中进行检查。

    【讨论】:

    • 这比检查属性要好。谢谢。
    • 嗯。我当前的解决方案(在我的问题中)检查IXmlSerializable[Serializable] 是否适用于给定的类TIsSerializable 是否兼顾两者?
    【解决方案2】:

    您不能要求将属性作为泛型的一部分。但是,您可以提供一个静态构造函数来检查它并在未找到时抛出。

    【讨论】:

      【解决方案3】:

      当类型没有正确序列化或反序列化时,我会消除类型约束并捕获 SerializationException...事实上,这允许您的通用 Serialize 和 Deserialize 方法接受格式化程序

      public enum Formatter { Binary, Xml }
      

      可以控制序列化是二进制还是Xml

      public class Serialization
      {
          public enum Formatter { Binary, Xml }
      
          #region Serialization methods
          public static void Serialize2File<T>(T obj, string pathSpec, 
              Formatter formatter)
          {
              try
              {
                  switch (formatter)
                  {
                      case (Formatter.Binary):
                          using (var fs = new FileStream(pathSpec, FileMode.Create,
                                              FileAccess.Write, FileShare.Write))
                              (new BinaryFormatter()).Serialize(fs, obj);
                          break;
      
                      case (Formatter.Xml):
                          var serializer = new XmlSerializer(typeof(T));
                          TextWriter textWriter = new StreamWriter(pathSpec);
                          serializer.Serialize(textWriter, obj);
                          textWriter.Close();
                          break;
      
                      default:
                          throw new MyCustomException("Invalid Formatter option");
                  }
              }
              catch (SerializationException sX)
              {
                  var errMsg = String.Format(
                      "Unable to serialize {0} into file {1}",
                      obj, pathSpec);
                  throw new MyCustomException(errMsg, sX);
              }
          }
          public static T DeSerializeFromFile<T>(string pathSpec, 
              Formatter formatter) where T : class
          {
              try
              {
                  switch (formatter)
                  {
                      case (Formatter.Binary):
                          using (var strm = new FileStream(pathSpec,
                                              FileMode.Open, FileAccess.Read))
                          {
                              IFormatter fmt = new BinaryFormatter();
                              var o = fmt.Deserialize(strm);
                              if (!(o is T))
                                  throw new ArgumentException("Bad Data File");
                              return o as T;
                          }
      
                      case (Formatter.Xml):
                          var serializer = new XmlSerializer(typeof(T));
                          TextReader rdr = new StreamReader(pathSpec);
                          return (T)serializer.Deserialize(rdr);
      
                      default:
                          throw new MyCustomException("Invalid Formatter option");
                  }
              }
              catch (SerializationException sX)
              {
                  var errMsg = String.Format(
                      "Unable to deserialize {0} from file {1}",
                      typeof(T), pathSpec);
                  throw new MyCustomException(errMsg, sX);
              }
          }
          #endregion Serialization methods
      }
      

      【讨论】:

      • 这不是一个不合理的解决方案。
      • 是的,我同意,它被一个开发人员使用,他知道他试图序列化的类是否是可序列化的,如果他用错了,那就是例外,你不能消除所有可能的编译时的错误。
      • @Ben:我们不能总是这样做,但我们当然应该尝试尽早并经常发现错误。在这种情况下,我们无法在编译时捕获它,但如果我们使用静态构造函数技巧,我们可以在运行时一开始就捕获它(这意味着编译后的烟雾检查不会错过它)。
      • 当我最初编写这个代码时,我在类中有代码来检测,(仅在尝试 Xml 序列化时),如果传入的类型变量实现 IXmlSerializable,或者(使用反射)被修饰带有[Serializable] 属性...然后WCF 出来了,他们添加了[DataContract] 属性,它还允许将类型序列化为Xml。所以我删除了它...
      【解决方案4】:

      C# 通用序列化实用程序类。第 1 部分。

      序列化实现 IXmlSerializable 或 [Serializable] 属性的类的核心是在将给定类型传递给序列化程序之前对其进行检查。

      string Serialize<T>(T o)
      {
          Type type = typeof(T);
          if (!(type.HasAttribute<SerializabeAttribute>()
              | type.ImplementsInterface<IXmlSerializable>()))
          {
              throw new InvalidOperationException("Unserializable object given.");
          }
          XmlSerializer serializer = new XmlSerializer(typeof(T));
          StringBuilder sb = new StringBuilder();
          using (XmlWriter xmlWriter = XmlWriter.Create(sb))
              serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces)null);
          return sb.ToString();
      }        
      

      出于这些目的,您应该实现以下扩展方法。

      using System.ComponentModel;
      using System.Linq;
      using System.Reflection;
      
      namespace System
      {
          public static partial class Extensions
          {
              /// <summary>
              /// Checks if the object <see cref="Type"/> has the specified attribute.
              /// </summary>
              /// <param name="type">
              /// Object <see cref="Type"/> for which you want to check whether
              /// whether it has <see cref="Attribute"/> specified by the <typeparamref name="T"/>.
              /// </param>
              public static bool HasAtribute<T>(this Type type) where T : Attribute
              {
                  return type.GetCustomAttributes(typeof(DataContractAttribute), true).Any();
              }
          
              /// <summary>
              /// Checks if the object <see cref="Type"/> implements the specified interface.
              /// </summary>
              /// <param name="type">
              /// Object <see cref="Type"/> for which you want to check whether
              /// whether it implements the interface specified by the <paramref name="interfaceType"/> parameter.
              /// </param>
              /// <param name="interfaceType">
              /// The <see cref="Type"/> being tested, which is an interface.
              /// </param>
              /// <exception cref="ArgumentNullException">
              /// <paramref name="type"/> is not a class, value type, or interface,
              /// and also if <paramref name="interfaceType"/> is not an interface.
              /// </exception>
              /// <exception cref="ArgumentException">
              /// The value <see langword="null"/> was passed as one of the parameters.
              /// </exception>
              /// <returns>
              /// <see langword="true"/> if the object <see cref="Type"/> implements the specified interface.
              /// </returns> 
              public static bool ImplementsInterface(this Type type, Type interfaceType)
              {
                  if (type == null)
                      throw new ArgumentNullException(nameof(type));
                  if (interfaceType == null)
                      throw new ArgumentNullException(nameof(interfaceType));
                  /*if (!(type.IsClass || type.IsValueType || type.IsInterface))
                      throw new ArgumentException(null, nameof(type));*/
                  if (!interfaceType.IsInterface)
                      throw new ArgumentException(
                          AssemblyMessageFormatter.DefaultFormatter.GetMessage("Arg_MustBeInterface"), 
                          nameof(interfaceType));
      
                  while (type != null)
                  {
                      Type[] interfaces = type.GetInterfaces();
                      {
                          int length = interfaces.Length;
                          for (int i = 0; i < length; i++)
                          {
                              if (interfaces[i] == interfaceType || interfaces[i].ImplementsInterface(interfaceType))
                                  return true;
                          }
                      }
                      type = type.BaseType;
                  }
                  return false;
              }
      
              /// <summary>
              /// Checks if the object <see cref="Type"/> implements the specified interface.
              /// </summary>
              /// <typeparam name="T">
              /// The type being checked, which is an interface.
              /// </typeparam>
              /// <param name="type">
              /// Object <see cref="Type"/> for which you want to check whether
              /// whether it implements the specified interface <typeparamref name="T"/>.
              /// </param>
              /// <returns>
              /// <see langword="true"/> if the object is <see cref="Type"/>
              /// implements the <typeparamref name="T"/> interface.
              /// </returns>
              /// <exception cref="ArgumentNullException">
              /// <paramref name="type"/> is not a class, value type, or interface.
              /// </exception>
              /// <exception cref="ArgumentException">
              /// The value <see langword="null"/> was passed as <paramref name="type"/>.
              /// </exception>
              public static bool ImplementsInterface<T>(this Type type) where T : class =>
                  ImplementsInterface(type, typeof(T)); 
      
          }
      }
      

      【讨论】:

        【解决方案5】:

        C# 通用序列化实用程序类。第 2 部分。

        这是一个 C# 通用序列化器:

        using System.IO;
        using System.Text;
        using System.Xml.Schema;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Linq;
        using System.Reflection;
        using System;
        
        namespace System.Xml.Serialization
        {
            /// <summary>
            /// Serializes and deserializes <typeparamref name="T"/> objects into XML documents.
            /// Allows you to control the process of encoding objects in XML.
            /// </summary>
            /// <typeparam name="T">Object type.</typeparam>
            public static class XmlSerializer<T>
            {
                private static readonly XmlSerializer _serializer = new XmlSerializer(typeof(T));
                private static readonly XmlWriterSettings _defaultWriterSettings = new XmlWriterSettings
                {
                    CheckCharacters = false
                    CloseOutput=false
                    ConformanceLevel = ConformanceLevel.Auto,
                    Encoding = Encoding.UTF8,
                    indent=true,
                    IndentChars = "\t",
                    NamespaceHandling = NamespaceHandling.OmitDuplicates,
                    NewLineChars = "\r\n",
                    NewLineHandling = NewLineHandling.Replace,
                    NewLineOnAttributes = false,
                    OmitXmlDeclaration = false
                };
                private static readonly XmlReaderSettings _defaultReaderSettings = new XmlReaderSettings
                {
                    CheckCharacters = false
                    CloseInput=false
                    ConformanceLevel = ConformanceLevel.Auto,
                    DtdProcessing = DtdProcessing.Prohibit,
                    IgnoreComments = true,
                    IgnoreProcessingInstructions = true,
                    IgnoreWhitespace=true,
                    LineNumberOffset = 0
                    LinePositionOffset = 0
                    MaxCharactersFromEntities = 0,
                    MaxCharactersInDocument = 0,
                    NameTable = null
                    // Schemas = null, // ???
                    ValidationFlags = XmlSchemaValidationFlags.None,
                    ValidationType = ValidationType. None,
                    XmlResolver = null
                }; 
                
                 /// <summary>
                 /// Default character encoding.
                 /// </summary>
                 public static Encoding DefaultEncoding => Encoding.UTF8;
        
                 /// <summary>
                 /// Default settings for the <see cref="XmlWriter" /> instance being created.
                 /// </summary>
                 public static XmlWriterSettings DefaultXmlWriterSettings => _defaultWriterSettings.Clone();
        
                 /// <summary>
                 /// Default settings for the <see cref="XmlReader" /> instance that is created.
                 /// </summary>
                 public static XmlReaderSettings DefaultXmlReaderSettings => _defaultReaderSettings.Clone();    
        
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and returns the XML document as a string.
                /// </summary>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                public static string Serialize(T o)
                {
                    StringBuilder sb = new StringBuilder();
                    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
                        _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces)null);
                    return sb.ToString();
                }
        
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and returns the XML document as a string.
                /// </summary>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlWriterSettings"/>.
                /// </param>
                public static string Serialize(T o, XmlWriterSettings settings)
                {
                    if (settings == null) settings = _defaultWriterSettings;
                    StringBuilder sb = new StringBuilder();
                    using (XmlWriter xmlWriter = XmlWriter.Create(sb, settings))
                        _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces)null);
                    return sb.ToString();
                }
        
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" />.
                /// </summary>
                /// <param name="textWriter">
                /// <see cref="TextWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                public static void Serialize(TextWriter textWriter, T o)
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
                        _serializer.Serialize(textWriter, o, (XmlSerializerNamespaces)null);
                } 
                
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" />.
                /// </summary>
                /// <param name="textWriter">
                /// <see cref="TextWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlWriterSettings"/>.
                /// </param>
                public static void Serialize(TextWriter textWriter, T o, XmlWriterSettings settings)
                {
                    if (settings == null) settings = _defaultWriterSettings;
                    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                        _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces)null);
                }
        
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" /> and references to the given namespaces.
                /// </summary>
                /// <param name="textWriter">
                /// <see cref="TextWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="namespaces">
                /// <see cref="XmlSerializerNamespaces" /> Contains the namespaces for the generated XML document.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(TextWriter textWriter, T o, XmlSerializerNamespaces namespaces)
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
                        _serializer.Serialize(xmlWriter, o, namespaces);
                } 
                
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" /> and references to the given namespaces.
                /// </summary>
                /// <param name="textWriter">
                /// <see cref="TextWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="namespaces">
                /// <see cref="XmlSerializerNamespaces" /> Contains the namespaces for the generated XML document.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlWriterSettings"/>.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(TextWriter textWriter, T o, XmlSerializerNamespaces namespaces, XmlWriterSettings settings)
                {
                    if (settings == null) settings = _defaultWriterSettings;
                    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                        _serializer.Serialize(xmlWriter, o, namespaces);
                }
        
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" />.
                /// </summary>
                /// <param name="stream">
                /// <see cref="Stream" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(Stream stream, T o)
                {
                    _serializer.Serialize(stream, o, (XmlSerializerNamespaces)null);
                } 
                
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" />.
                /// </summary>
                /// <param name="stream">
                /// <see cref="Stream" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlWriterSettings"/>.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(Stream stream, T o, XmlWriterSettings settings)
                {
                    if (settings == null) settings = _defaultWriterSettings;
                    using (TextWriter writer = new StreamWriter(stream, settings.Encoding))
                    using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
                        _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces) null);
                }
        
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" /> refers to the given namespaces.
                /// </summary>
                /// <param name="stream">
                /// <see cref="Stream" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="namespaces">
                /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(Stream stream, T o, XmlSerializerNamespaces namespaces)
                {
                    _serializer.Serialize(stream, o, namespaces);
                } 
                
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" /> refers to the given namespaces.
                /// </summary>
                /// <param name="stream">
                /// <see cref="Stream" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="namespaces">
                /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlWriterSettings"/>.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(Stream stream, T o, XmlSerializerNamespaces namespaces, XmlWriterSettings settings)
                {
                    if (settings == null) settings = _defaultWriterSettings;
                    using (TextWriter writer = new StreamWriter(stream, settings.Encoding))
                    using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
                        _serializer.Serialize(xmlWriter, o, namespaces);
                }
        
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="XmlWriter" />.
                /// </summary>
                /// <param name="xmlWriter">
                /// <see cref="XmlWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// the settings of the current <see cref="XmlWriter" /> instance are used.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(XmlWriter xmlWriter, T o, XmlWriterSettings settings = null)
                {
                    using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                        _serializer.Serialize(writer, o, (XmlSerializerNamespaces)null); 
                }
                
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="XmlWriter" /> and references to the given namespaces.
                /// </summary>
                /// <param name="xmlWriter">
                /// <see cref="XmlWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">
                /// An instance <typeparamref name="T"/> to serialize.
                /// </param>
                /// <param name="namespaces">
                /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// the settings of the current <see cref="XmlWriter" /> instance are used.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(XmlWriter xmlWriter, T o, XmlSerializerNamespaces namespaces, XmlWriterSettings settings = null)
                {
                    using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                        _serializer.Serialize(writer, o, namespaces);
                }
        
                /// <summary>
                /// Serializes the specified object and writes the XML document to a file using the specified <typeparamref name="T"/> and references the specified namespaces and encoding style.
                /// </summary>
                /// <param name="xmlWriter">
                /// <see cref="XmlWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">Object to serialize.</param>
                /// <param name="namespaces">
                /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
                /// </param>
                /// <param name="encodingStyle">
                /// The encoding style of the serialized XML.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// the settings of the current <see cref="XmlWriter" /> instance are used.
                /// </param>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during serialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static void Serialize(
                    XmlWriter xmlWriter,
                    T o
                    XmlSerializerNamespaces,
                    string encodingStyle,
                    XmlWriterSettings settings = null)
                {
                    using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                        _serializer.Serialize(writer, o, namespaces, encodingStyle, (string)null);
                } 
                
                /// <summary>
                /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="XmlWriter" />, XML namespaces, and encoding.
                /// </summary>
                /// <param name="xmlWriter">
                /// <see cref="XmlWriter" /> Used to write an XML document.
                /// </param>
                /// <param name="o">Object to serialize.</param>
                /// <param name="namespaces">
                /// An instance of <see langword="XmlSerializaerNamespaces" /> containing the namespaces and prefixes used.
                /// </param>
                /// <param name="encodingStyle">
                /// The encoding used in the document.
                /// </param>
                /// <param name="id">
                /// For SOAP encoded messages, a base is used to generate identifier attributes.
                /// </param>
                /// <param name="settings">
                /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
                /// the settings of the current <see cref="XmlWriter" /> instance are used.
                /// </param>
                public static void Serialize(
                    XmlWriter xmlWriter,
                    T o
                    XmlSerializerNamespaces,
                    string encodingStyle,
                    string id,
                    XmlWriterSettings settings = null)
                {
                    using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                        _serializer.Serialize(writer, o, namespaces, encodingStyle, id);
                } 
                
                /// <summary>
                /// Deserializes the XML document contained in the specified string.
                /// </summary>
                /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
                /// <returns> The deserialized object <typeparamref name="T"/>. </returns>
                public static T Deserialize(string text)
                {
                    using (StringReader reader = new StringReader(text))
                    using (XmlReader xmlReader = XmlReader.Create(reader))
                        return (T)_serializer.Deserialize(xmlReader);
        
                }
        
                /// <summary>
                /// Deserializes the XML document contained in the specified string.
                /// </summary>
                /// <param name="text">String containing the XML document.</param>
                /// <param name="settings"> Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
                /// <returns> The deserialized object <typeparamref name="T"/>. </returns>
                public static T Deserialize(string text, XmlReaderSettings settings)
                {
                    if (settings == null) settings = _defaultReaderSettings;
                    using (StringReader reader = new StringReader(text))
                    using (XmlReader xmlReader = XmlReader.Create(reader, settings))
                        return (T)_serializer.Deserialize(xmlReader);
        
                }
        
                /// <summary>
                /// Deserializes the XML document contained in the specified <see cref="Stream" />.
                /// </summary>
                /// <param name="stream">
                /// <see cref="Stream" /> Containing the XML document to deserialize.
                /// </param>
                /// <returns>
                /// Deserialized object <typeparamref name="T"/>.
                /// </returns>
                public static T Deserialize(Stream stream)
                {
                        return (T)_serializer.Deserialize(stream);
                } 
                
                /// <summary>
                /// Deserializes the XML document contained in the specified <see cref="Stream" />.
                /// </summary>
                /// <param name="stream">
                /// <see cref="Stream" /> Containing the XML document to deserialize.
                /// </param>
                /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
                /// <returns>
                /// Deserialized object <typeparamref name="T"/>.
                /// </returns>
                public static T Deserialize(Stream stream, XmlReaderSettings settings)
                {
                    if (settings == null) settings = _defaultReaderSettings;
                    using(XmlReader xmlReader = XmlReader.Create(stream, settings))
                        return (T)_serializer.Deserialize(xmlReader);
                }
        
                /// <summary>
                /// Deserializes the XML document contained in the specified <see cref="TextReader" />.
                /// </summary>
                /// <param name="textReader">
                /// <see cref="TextReader" /> The containing XML document to deserialize.
                /// </param>
                /// <returns>
                /// Deserialized object <typeparamref name="T"/>.
                /// </returns>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during deserialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static T Deserialize(TextReader textReader)
                {
                    return (T) _serializer.Deserialize(textReader);
                }
        
                /// <summary>
                /// Deserializes the XML document contained in the specified <see cref="TextReader" />.
                /// </summary>
                /// <param name="textReader">
                /// <see cref="TextReader" /> The containing XML document to deserialize.
                /// </param>
                /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
                /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
                /// <returns>
                /// Deserialized object <typeparamref name="T"/>.
                /// </returns>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during deserialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static T Deserialize(TextReader textReader, XmlReaderSettings settings)
                {
                    if (settings == null) settings = _defaultReaderSettings;
                    using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                        return (T)_serializer.Deserialize(xmlReader);
                } 
                
                /// <summary>
                /// Deserializes the XML document contained in the specified <see cref="XmlReader" />.
                /// </summary>
                /// <param name="xmlReader">
                /// <see cref="XmlReader" /> The containing XML document to deserialize.
                /// </param>
                /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
                /// current instance settings are used <see cref="XmlReader" />.</param>
                /// <returns>
                /// Deserialized object <typeparamref name="T"/>.
                /// </returns>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during deserialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static T Deserialize(XmlReader xmlReader, XmlReaderSettings settings = null)
                {
                    using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                        return (T)_serializer.Deserialize(xmlReader);
                }
        
                /// <summary>
                /// Deserializes the XML document contained in the specified <see cref="XmlReader" /> and allows you to override events that occur during deserialization.
                /// </summary>
                /// <param name="xmlReader">
                /// <see cref="XmlReader" /> The containing document to deserialize.
                /// </param>
                /// <param name="events">
                /// Class instance <see cref="XmlDeserializationEvents" />.
                /// </param>
                /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
                /// current instance settings are used <see cref="XmlReader" />.</param>
                /// <returns>
                /// Deserialized object <typeparamref name="T"/>.
                /// </returns>
                public static T Deserialize(XmlReader xmlReader, XmlDeserializationEvents events, XmlReaderSettings settings = null)
                {
                    using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                        return (T)_serializer.Deserialize(reader, (string)null, events);
                }
        
                /// <summary>
                /// Deserializes the XML document contained in the specified <see cref="XmlReader" /> and encoding style.
                /// </summary>
                /// <param name="xmlReader">
                /// <see cref="XmlReader" /> The containing XML document to deserialize.
                /// </param>
                /// <param name="encodingStyle">
                /// The encoding style of the serialized XML.
                /// </param>
                /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
                /// current instance settings are used <see cref="XmlReader" />.</param>
                /// <returns>The deserialized object.</returns>
                /// <exception cref="InvalidOperationException">
                /// An error occurred during deserialization.
                /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
                /// </exception>
                public static T Deserialize(XmlReader xmlReader, string encodingStyle, XmlReaderSettings settings = null)
                {
                    using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                        return (T)_serializer.Deserialize(reader, encodingStyle);
                }
        
                /// <summary>
                /// Deserializes the object using the data contained in the specified <see cref="XmlReader" />.
                /// </summary>
                /// <param name="xmlReader">
                /// An instance of the <see cref="XmlReader" /> class used to read the document.
                /// </param>
                /// <param name="encodingStyle">Encoding used.</param>
                /// <param name="events">
                /// Class instance <see cref="XmlDeserializationEvents" />.
                /// </param>
                /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
                /// current instance settings are used <see cref="XmlReader" />.</param>
                /// <returns>The deserialized object <typeparamref name="T"/>.</returns>
                public static object Deserialize(
                    xmlReader xmlReader,
                    string encodingStyle,
                    XmlDeserializationEvents events,
                    XmlReaderSettings settings = null)
                {
                    using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                        return _serializer.Deserialize(reader, encodingStyle, events);
                }
        
                /// <summary>
                /// Returns a value indicating whether this <see cref="XmlSerializer" /> can deserialize the specified XML document.
                /// </summary>
                /// <param name="xmlReader">
                /// <see cref="XmlReader" /> Pointing to the document to deserialize.
                /// </param>
                /// <returns>
                /// <see langword="true" /> If this <see cref="XmlSerializer" /> can deserialize an object, <see cref="XmlReader" /> indicates; otherwise, <see langword="false" />.
                /// </returns>
                public static bool CanDeserialize(XmlReader xmlReader)
                {
                    return _serializer.CanDeserialize(xmlReader);
                } 
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-12
          • 1970-01-01
          • 2021-12-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多