Xml输出类到泛型类

时间:2017-05-31 18:50:30

标签: c# xml class

我在另一篇文章中找到了我正在尝试修改的课程。

using System;
using System.IO;

namespace Misc
{
  internal class ConfigManager
  {

    private string _sConfigFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("{0}.xml", AppDomain.CurrentDomain.FriendlyName));
    private Config m_oConfig = new Config();

    public Config MyConfig
    {
      get { return m_oConfig; }
      set { m_oConfig = value; }
    }

    // Load configuration file
    public void LoadConfig()
    {
      if (System.IO.File.Exists(_sConfigFileName))
      {
        System.IO.StreamReader srReader = System.IO.File.OpenText(_sConfigFileName);
        Type tType = m_oConfig.GetType();
        System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
        object oData = xsSerializer.Deserialize(srReader);
        m_oConfig = (Config)oData;
        srReader.Close();
      }
    }

    // Save configuration file
    public void SaveConfig()
    {
      System.IO.StreamWriter swWriter = System.IO.File.CreateText(_sConfigFileName);
      Type tType = m_oConfig.GetType();
      if (tType.IsSerializable)
      {
        System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
        xsSerializer.Serialize(swWriter, m_oConfig);
        swWriter.Close();
      }
    }

  }
}

我想传入一个X类型的对象并保存它。在同一个前提下,我想传入一个类型并让它传回X类型的对象。现在,使用Config进行硬编码。所以,如果有一种传递类对象(?)的方法,那么我希望它将它保存为该对象和/或返回该对象。

这可能吗?如果是这样,我将如何做到这一点?

2 个答案:

答案 0 :(得分:0)

使用泛型:

internal class ConfigManager<T>
{
    private string _fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("{0}.xml", AppDomain.CurrentDomain.FriendlyName));
    private T _config;
    private XmlSerializer serializer = new XmlSerializer(typeof(T));

    public T MyConfig
    {
        get { return _config; }
        set { _config = value; }
    }

    public void LoadConfig()
    {
        if (File.Exists(_fileName))
        {
            using (var reader = File.OpenText(_fileName))
            {
                _config = (T)serializer.Deserialize(reader);
            }
        }
    }

    public void SaveConfig()
    {
        using (var writer = File.CreateText(_fileName))
        {
            serializer.Serialize(writer, _config);
        }
    }
}

用法:

var man = new ConfigManager<Foo>();

答案 1 :(得分:0)

基本上,我们需要让它与Generics一起使用。因此,我们首先给它一个类型变量,并用Config替换类T的每次使用:

 internal class Manager<T>
 {
      private T m_oObj;      // etc

接下来,我会做一个方法;你可以做其余的事。 (我删除了显式名称空间,因为它们很难看)

using System.IO;
using System.Xml.Serialization;

public void LoadConfig<T>()
{
  if (File.Exists(_sConfigFileName))
  {
    var  srReader = File.OpenText(_sConfigFileName);
    var  xsSerializer = new XmlSerializer(typeof(T));
    var  oData = xsSerializer.Deserialize(srReader);
    m_oObj = (T)oData;
    srReader.Close();
  }
}