泛型方法中的类型转换



我需要使这个类尽可能通用…我想传递一个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;
        }         
    }
}

我知道我应该使用反射,但我有问题,使这个cast data = (type)xmlfile.Deserialize(xmlStream);

谢谢…

你可以这样做:

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

相关内容

  • 没有找到相关文章

最新更新