c# - 可以使用泛型来折叠这些方法吗?

标签 c# generics

我有两个方法,它们做的事情非常相似,但返回类型不同(字符串与整数)

他们在这里:

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

以下是 stringint 的一些示例用例

LoadAttribute(xmlElement, someName, x => x, defaultValue);  // string
LoadAttribute(xmlElement, someName, Int32.Parse, defaultValue);  // int

关于c# - 可以使用泛型来折叠这些方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4796241/

相关文章:

c# - 图节点坐标评估

swift - 在实现测量扩展中,我们可以使用通用的 UnitType 吗?

ios - 将模型类传递给嵌套方法时出现 Swift 泛型方法问题

c# - 记录和恢复应用程序状态以快速启动 .NET 应用程序

c# - 我不明白基类的继承

C# 锁定私有(private)静态对象

java - 使用泛型限制容器

c# - 在 Unity 中使用反射注册通用类型

java - 为什么它不允许我使用泛型执行此类作业?

c# - 将嵌套循环重构为单个 LINQ 查询