为什么. any()不能在这个特定的XElement扩展方法中工作?

本文关键字:扩展 XElement 方法 工作 any 不能 为什么 | 更新日期: 2023-09-27 18:13:57

我做了一个简单的方法,从一个特定的节点返回一个字符串值(或者如果它不存在返回null)。

private static string getValueIfExist(XElement element, string nodeName)
{    
  return element.Elements(nodeName).Any() ? element.Elements(nodeName).First().Value : null;
}

现在我想使用这个方法作为XElement的扩展方法:

public static string GetValueIfExist(this XElement element, string nodeName)
{
  return element.Elements(nodeName).Any() ? element.Elements(nodeName).First().Value : null;
}

但是它不能编译。由于某些原因,Any()和First()不再被视为IEnumerable的一部分。我做错了什么?是否有其他方法来获得这个特定的扩展方法?

为什么. any()不能在这个特定的XElement扩展方法中工作?

解决方案非常简单…延斯·克洛斯特的思路是对的。我忘了在Extensions类中包含System.Linq名称空间。当我第一次检查包含并看到包含System.Xml.Linq时,我认为这就是我所需要的。但现在我意识到我需要这两个名称空间。

我还注意到Visual Studio 2012没有为这种特殊情况提供"Resolve"菜单项,当您右键单击Any()时

你需要让你的类static

public static class Extensions
{
   public static string GetValueIfExist(this XElement element, string nodeName)
   {
      ...
   }
}