-1

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

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);
4

1 回答 1

0
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");
    }
  }
于 2013-08-28T11:03:45.900 回答