gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:18:29 25 4
gpt4 key购买 nike

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

我有几个不同的设置文件,我有一个 GetData 方法,它接收一个“路径”参数。

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

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

是否最好执行一些操作,例如传递 ref 参数并以这种方式从对象获取类型?

谢谢!

最佳答案

改用泛型方法:

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

关于c# - 如何根据参数转换对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12607356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com