1

我有一个我想概括的方法。我想对任何对象类型使用以下反序列化函数,如下所示:

ExportDefinition _expDefinition = new ExportDefinition("a.ini");
DeliveryDefinition _delDefinition = new DeliveryDefinition("b.ini");

ExportDefinition expDef = Deserialize(_expDefinition);
DeliveryDefinition devDef = Deserialize(_delDefinition);

public SomeType Deserialize(SomeType?? tp)  // What should I use instead of SomeType?
{     
    try
    {
        FileStream readFileStream = new FileStream(definitionFile, FileMode.Open, FileAccess.Read, FileShare.Read);

        XmlSerializer serializerObj = new XmlSerializer(typeof(tp));
        tp loadedObj = (tp)serializerObj.Deserialize(readFileStream);
        readFileStream.Close();
     }
     catch (Exception ex)
     {
        throw new Exception(ex.Message);
     }

     return loadedObj;
}

任何想法,如何实现这一目标?

4

1 回答 1

6

使用泛型:

    public T Deserialize<T>(string filePath)
    {
        Stream stream = null;

        try
        {
            stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            XmlSerializer serializerObj = new XmlSerializer(typeof(T));

            return (T)serializerObj.Deserialize(stream);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (stream != null)
            {
                stream.Close();
            }
        }
    }

基于 Marc Gravell 的有用评论的非通用版本:

public object Deserialize(string filePath, Type type)
{
    Stream stream = null;

    try
    {
        stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
        XmlSerializer serializerObj = new XmlSerializer(type);

        return serializerObj.Deserialize(stream);
    }
    catch (Exception)
    {
        // Put something useful here
        throw;
    }
    finally
    {
        if (stream != null)
        {
            stream.Close();
        }
    }
}
于 2013-01-21T12:43:43.777 回答