C# XElement.Elements().Select()尝试显式指定类型参数

C# XElement.Elements().Select()尝试显式指定类型参数,c#,linq-to-xml,C#,Linq To Xml,我有一个奇怪的问题,想知道是什么原因造成的 我有以下XML: <categories> <category Name="Generic" Id="0"></category> <category Name="Development Applications" Id="2"></category> <category Name="Standard Templates" Id="5"></category>

我有一个奇怪的问题,想知道是什么原因造成的

我有以下XML:

<categories>
  <category Name="Generic" Id="0"></category>
  <category Name="Development Applications" Id="2"></category>
  <category Name="Standard Templates" Id="5"></category>      
  <category Name="Testing" Id="9" />
</categories>
其中:

private static Category MapCategory(XElement element)
{
    var xAttribute = element.Attribute("Name");
    var attribute = element.Attribute("Id");
    return attribute != null && xAttribute != null 
        ? new Category(xAttribute.Value, attribute.Value) 
        : null;
}
在编译之前,没有任何错误/警告等表明这是错误的,但是编译后我收到以下消息,但仍然没有红色下划线:

无法从用法推断方法“System.Linq.Enumerable.SelectSystem.Collections.Generic.IEnumerable,System.Func”的类型参数。尝试显式指定类型参数

现在,如果我将所讨论的行更改为以下内容,则一切正常:

var categories = xElement.Elements().Select<XElement, Category>(MapCategory).ToList();
让我更加困惑的是,我让另一个开发人员也尝试了代码,他根本没有得到任何编译错误

你知道为什么会这样吗

让我更加困惑的是,我让另一个开发人员也尝试了代码,他根本没有得到任何编译错误

我猜您使用的是与您的同事不同的C编译器版本

这不仅限于LINQ到XML,也不限于元素调用的使用。如果您有以下情况,我相信您会看到相同的行为:

private static string ConvertToString(int x) { ... }

...
IEnumerable<int> values = null; // We're only testing the compiler here...
IEnumerable<string> strings = values.Select(ConvertToString);

哼!现在觉得自己很愚蠢,和我的同事核对过,他用的是4,我用的是3.5。还注意到ReSharper知道C4,并用它来识别警告。
var categories2 = doc.Element("categories").Elements().Select(element =>
            { new Category(element.Attribute("Name").Value, element.Attribute("Id").Value); }).ToList();
private static string ConvertToString(int x) { ... }

...
IEnumerable<int> values = null; // We're only testing the compiler here...
IEnumerable<string> strings = values.Select(ConvertToString);
...Elements().Select(x => MapCategory(x))...