我很难尝试创建 XmlRepository。这里的问题我只能选择使用 XmlSerializer 来做到这一点。
请检查一下。我的代码真的很乱,令人沮丧。我想知道如何改进这段代码,我正在考虑创建一个单例,但我不确定如何继续。
public interface IRepository<T>
where T : class
{
T GetById(object id);
IEnumerable<T> All();
void Insert(T entity);
void Remove(T entity);
void SaveChanges();
}
public class XmlRepository : IRepository<Configuration>
{
public XmlRepository(string filename)
{
FileName = filename;
}
public XmlRepository(string filename)
{
FileName = filename;
}
internal string FileName { get; private set; }
private Configuration GetById(object id)
{
throw new NotImplementedException();
}
public IEnumerable<Configuration> All()
{
return Get();
}
public void Insert(Configuration entity)
{
var configurations = Get();
configurations.Add(entity);
Save(configurations);
}
public void Remove(Configuration entity)
{
var configurations = Get();
configurations.Remove(entity);
Save(configurations);
}
private List<Configuration> Get()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Configuration>), null, new Type[] { typeof(BinaryConfiguration) }, new XmlRootAttribute("Configurations"), "http://ofimbres.wordpress.com/");
StreamReader myWriter = new StreamReader(FileName);
var list = serializer.Deserialize(myWriter);
myWriter.Close();
return (List<Configuration>)list;
}
catch (InvalidOperationException ex)
{
throw ex;
}
}
public void Save(object configurations)
{
try
{
XmlSerializer serializer = new XmlSerializer(configurations.GetType(), null, new Type[] { typeof(BinaryConfiguration) }, new XmlRootAttribute("Configurations"), "http://ofimbres.wordpress.com/");
StreamWriter myWriter = new StreamWriter(FileName);
serializer.Serialize(myWriter, configurations);
myWriter.Close();
}
catch (XmlException ex)
{
throw ex;
}
}
}
有任何疑问,请告诉我。非常感谢