如何概括一个方法

时间:2013-01-21 12:41:36

标签: c#

我有一个我想要概括的方法。我想对任何对象类型使用以下Deserialize函数,如belew:

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

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

1 个答案:

答案 0 :(得分: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();
        }
    }
}