2

我遇到了一个奇怪的问题,想知道可能是什么原因造成的。

我有以下 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>

以及以下代码来创建“类别”列表:

var doc = XDocument.Load("categories.xml");

var xElement = doc.Element("categories");
if (xElement == null) return;

var categories = xElement.Elements().Select(MapCategory).ToList();

在哪里:

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.Select<TSource,TResult>(System.Collections.Generic.IEnumerable, System.Func<TSource,TResult>)' 的类型参数。尝试明确指定类型参数。

现在,如果我将有问题的行更改为以下内容,一切都很好:

var categories = xElement.Elements().Select<XElement, Category>(MapCategory).ToList();

我会认为这Select<XElement, Category>是多余的???ReSharper 也同意我的看法。

为了确保,我删除了 MapCategory 并将其替换为以下内容,但这次我得到了红色下划线和一个编译错误:

var categories2 = doc.Element("categories").Elements().Select(element =>
            { new Category(element.Attribute("Name").Value, element.Attribute("Id").Value); }).ToList();

只是为了增加我的困惑,我让另一位开发人员也尝试了代码,他根本没有遇到任何编译错误。

任何想法为什么会发生这种情况?

4

1 回答 1

3

只是为了增加我的困惑,我让另一位开发人员也尝试了代码,他根本没有遇到任何编译错误。

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

这不仅限于 LINQ to XML 或Elements()调用的使用。如果您有以下情况,我相信您会看到相同的行为:

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

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

基本上,使用方法组转换的泛型方法调用的类型推断在 C# 4 编译器中得到了改进。(我认为C# 5 编译器可能也有所改进,但我记不清了。)明确指定类型参数的另一种方法是使用 lambda 表达式:

...Elements().Select(x => MapCategory(x))...
于 2012-09-11T00:48:23.170 回答