如何根据参数转换对象类型?

kod*_*kas 2 c# casting xml-deserialization

我有一个简单的问题,但我不确定处理它的最佳方法是什么.

我有几个不同的设置文件,我有一个GetData方法,它接收'path'参数.

        public static CountriesInfo GetDataFromFile(string path)
    {
        if (!File.Exists(path))
        {
            return null;
        }

        try
        {
            CountriesInfo tempData = new CountriesInfo();
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(tempData.GetType());
            StreamReader tempReader = new StreamReader(path);
            tempData = (CountriesInfo)x.Deserialize(tempReader);
            tempReader.Close();
            return tempData;
        }
        catch
        {
            return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

重构这个以支持传递对象类型,然后从方法中进行强制转换的最佳方法是什么?现在返回类型(在这个例子中)是CountriesInfo,但是我不希望有几个相同的函数,唯一的区别是返回类型和方法中的转换.

是否最好做一些像传递ref参数并从那个方式获取对象类型的东西?

谢谢!

car*_*ira 7

改为使用通用方法:

public static T GetDataFromFile<T>(string path) where T : class
{ 
    if (!File.Exists(path)) 
    { 
        return null; 
    } 

    try 
    { 
        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T)); 
        StreamReader tempReader = new StreamReader(path); 
        T result = (T)x.Deserialize(tempReader); 
        tempReader.Close(); 
        return result; 
    } 
    catch 
    { 
        return null; 
    } 
} 
Run Code Online (Sandbox Code Playgroud)