2013-08-28 43 views
-1

我有一個很大的解決方案,有很多序列化器/解串器+接口。 我想減少文件數量,但保持代碼的可測試性和可讀性。 我在尋找一些串行提供商(不是工廠),例如:C#testable序列化類

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

回答

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"); 
    } 
    }