我有两个方法,它们做的事情非常相似,但返回类型不同(字符串与整数)
他们在这里:
private static string LoadAttributeString(this XElement xmlElement,
string attributeName, string defaultValue)
{
try
{return xmlElement.Attribute(attributeName).Value;}
catch (Exception)
{return defaultValue;}
}
private static int LoadAttributeInt(this XElement xmlElement,
string attributeName, int defaultValue)
{
try
{return int.Parse(xmlElement.Attribute(attributeName).Value);}
catch (Exception)
{return defaultValue;}
}
是否可以使用泛型将这些组合成一个方法? (我尝试过但失败了。)
注意:我可以使用两种不同的方法。我只想扩展我对泛型的了解。所以我想我会问是否可能。
最佳答案
尝试以下操作
private static T LoadAttribute<T>(
this XElement xmlElement,
string attributeName,
Func<string, T> convertFunc,
T defaultValue) {
try {
return convertFunc(xmlElement.Attribute(attributeName).Value);
} catch (Exception) {
return defaultValue;
}
}
以下是 string
和 int
的一些示例用例
LoadAttribute(xmlElement, someName, x => x, defaultValue); // string
LoadAttribute(xmlElement, someName, Int32.Parse, defaultValue); // int
关于c# - 可以使用泛型来折叠这些方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4796241/