C#可测试的序列化类

本文关键字:序列化 测试 | 更新日期: 2023-09-27 18:29:14

我有一个很大的解决方案,其中包含许多序列化程序/反序列化程序+接口。我想减少文件数量,但保持代码的可测试性和可读性。我正在搜索一些序列化程序提供商(不是工厂),例如:

interface ISerializable
    {
        string Serialize<T>(T obj);
        T Deserialize<T>(string xml);
    }
    class Serializable : ISerializable
    {
        public string Serialize<T>(T obj)
        {
            return this.ToXml(obj);
        }
        public T Deserialize<T>(string xml)
        {
            throw new System.NotImplementedException();
        }
    }
    internal static class Serializers
    {
        public static string ToXml(this Serializable s, int value)
        {
        }
        public static string ToXml(this Serializable s, SomeType value)
        {
        }
    }

在这种情况下,我需要添加一个新的扩展来序列化某些类型。但通用接口将保留:

ISerializable provider;
provider.Serialize<SomeType>(obj);

C#可测试的序列化类

using System;
using System.IO;
namespace ConsoleApplication2
{
  using System.Runtime.Serialization;
  using System.Xml;
  public interface ISerializable
  {
    void Serialize<T>(T obj, string xmlFile);
    T Deserialize<T>(string xmlFile);
  }
  public class Serializable : ISerializable
  {
    public void Serialize<T>(T obj, string xmlFile)
    {
      Stream xmlStream = null;
      try
      {
        xmlStream = new MemoryStream();
        var dcSerializer = new DataContractSerializer(typeof(T));
        dcSerializer.WriteObject(xmlStream, obj);
        xmlStream.Position = 0;
        // todo Save the file here USE DATACONTRACT
      }
  catch (Exception e)
  {
    throw new XmlException("XML error", e);
  }
  finally
  {
    if (xmlStream != null)
    {
      xmlStream.Close();
    }
  }
}
 public T Deserialize<T>(string xmlFile)
{
  FileStream fs = null;
  try
  {
    fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    if (fs.CanSeek)
    {
      fs.Position = 0;
    }
    var dcSerializer = new DataContractSerializer(typeof(T));
    var value = (T)dcSerializer.ReadObject(fs);
    fs.Close();
    return value;
  }
  catch (Exception e)
  {
    throw new XmlException("XML error", e);
  }
  finally
      {
     if (fs != null)
        {
          fs.Close();
        }
      }
    }
  }    
  [DataContract]
  public class A
  {
    [DataMember]
    public int Test { get; set; }
  }
  public class test
  {
    public test()
    {
      var a = new A { Test = 25 };
      var ser = new Serializable();
      ser.Serialize(a, "c:''test.xml");
      var a2 = ser.Deserialize<A>("c:'test.xml");
      if (a2.Test == a.Test)
        Console.WriteLine("Done");
    }
  }