通用方法

时间:2015-10-16 11:57:33

标签: c# .net reflection

我需要使这个类尽可能通用...我想传递一个XML字符串Path并返回我传递给getDataFromFile()方法的对象类型的数据。 这是我到目前为止所做的:

public class XmlFile
{
    public string mXmlFilePath { get; set; }

    public XmlFile(string xmlFilePath)
    {
        this.mXmlFilePath = xmlFilePath;
    }

    public object getDataFromFile(object dataObject)
    {
        LogFile.addLogEntry("Getting data from XML file.");

        object data = null;
        Type type = dataObject.GetType();

        try
        {

            StreamReader xmlStream = new StreamReader(this.mXmlFilePath);
            XmlSerializer xmlfile = new XmlSerializer(type);
            data = (type)xmlfile.Deserialize(xmlStream);
            xmlStream.Close();
            return data;
        }
        catch (Exception ex)
        {
            LogFile.addLogEntry("Error reading data from XML file: " + ex.Message);
            return null;
        }         
    }
}

我知道我应该使用反射,但是我在制作这个演员时遇到了麻烦data = (type)xmlfile.Deserialize(xmlStream);

谢谢......

1 个答案:

答案 0 :(得分:0)

你可以这样做:

public T getDataFromFile<T>()
{
    LogFile.addLogEntry("Getting data from XML file.");
    try
    {
        using(StreamReader xmlStream = new StreamReader(this.mXmlFilePath))
        {
            XmlSerializer xmlfile = new XmlSerializer(typeof(T));
            return (T)xmlfile.Deserialize(xmlStream);
        }
    }
    catch (Exception ex)
    {
        LogFile.addLogEntry("Error reading data from XML file: " + ex.Message);
        return null;
    }
}