私は奇妙な問題を抱えており、何が原因なのか疑問に思っていました。
次の 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();
私の混乱に加えて、別の開発者にもコードを試してもらいましたが、コンパイル エラーはまったく発生しませんでした。
なぜこれが起こっているのでしょうか?