2014-07-20 39 views
-1

我做了一個簡單的方法,它從特定節點返回一個字符串值(或者如果它不存在,則返回null)。爲什麼.Any()在這個特定的XElement擴展方法中不起作用?

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的一部分。我究竟做錯了什麼?是否有另一種方法來獲得這種特定的擴展方法?

+0

你得到的錯誤是什麼? – svick

+0

您是否添加了System.Linq命名空間? –

+0

爲什麼你需要這種擴展方法?聽起來好像是'(string)element.Element(nodeName)'應該做的。或者'(string)element.Elements(nodeName).FirstOrDefault()'。 –

回答

0

你也需要讓你的班級static

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

我知道。我在單獨的擴展類中使用擴展方法。但是如果你嘗試上面的代碼,你會發現Visual Studio開始抱怨缺少.Any()和.First()方法。 – CameO73

1

解決方案變得非常簡單......延斯克洛斯特走在了正確的軌道上。我忘記在我的擴展類中包含System.Linq命名空間。我第一次檢查包括,並看到包括System.Xml.Linq,我認爲這是我所需要的。但是現在我意識到我需要兩個命名空間。

我還注意到,當您右鍵單擊任何()時,Visual Studio 2012不會爲這個特定情況提供「解析」菜單項。

相關問題