泛型可以用来折叠这些方法吗?

Vac*_*ano 2 c# generics

我有两个方法做非常相似的事情,但有不同的返回类型(字符串vs int)

他们来了:

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;}
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用泛型将这些方法组合成一种方法?(我尝试过但失败了.)

注意:我有两种不同的方法.我想扩展我对泛型的了解.所以我想我会问是否有可能.

Jar*_*Par 6

请尝试以下方法

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是一些示例用例stringint

LoadAttribute(xmlElement, someName, x => x, defaultValue);  // string
LoadAttribute(xmlElement, someName, Int32.Parse, defaultValue);  // int
Run Code Online (Sandbox Code Playgroud)