using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using ConfigurationTool.CustomSerializer;
using RW_Tool.Interface;
using RW_Tool.DataSource.FileOrStream;
namespaceConfigurationTool.RW.Bin
{
publicclassBin_Reader<T> : IReader<T, DS_FileOrStream>
whereT : class, new()
{
public T Read(DS_FileOrStream ds)
{
switch (ds.Type)
{
case"File": return ReadFile(ds.AsFile.FilePath);
case"Stream": return ReadStream(ds.AsStream.Stream);
default: thrownew Exception();
}
}
public T ReadFile(string file)
{
if (typeof(T).GetInterface("ICustomSerialazible") == null)
{
// передаем в конструктор тип класса
BinaryFormatter formatter = new BinaryFormatter();
// десериализацияusing (FileStream fs = new FileStream(file, FileMode.Open))
{
return (T)formatter.Deserialize(fs);
}
}
else
{
ICustomSerialazible res = (ICustomSerialazible)new T();
// передаем в конструктор тип класса
BinaryFormatter formatter = new BinaryFormatter();
// десериализацияusing (FileStream fs = new FileStream(file, FileMode.Open))
{
res.Import(formatter.Deserialize(fs));
}
return (T)res;
}
}
public T ReadStream(Stream stream)
{
if (typeof(T).GetInterface("ICustomSerialazible") == null)
{
// передаем в конструктор тип класса
BinaryFormatter formatter = new BinaryFormatter();
// десериализация return (T)formatter.Deserialize(stream);
}
else
{
ICustomSerialazible res = (ICustomSerialazible)new T();
// передаем в конструктор тип класса
BinaryFormatter formatter = new BinaryFormatter();
// десериализация
res.Import(formatter.Deserialize(stream));
return (T)res;
}
}
}
}