Does LINQ “Query Syntax” Support Duck Typing?

后端 未结 2 1722
情书的邮戳
情书的邮戳 2021-01-17 05:08

Regarding LINQ query syntax...

var foo = new List { 1, 2 };

var boo = from n in foo
            where n > 1
            select n;
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 05:23

    There are a few features in C# that the compiler does structural type matching rather than nominal type matching. Examples include the foreach loop, query comprehension syntax (the select, where, etc), and await/async. For all of these features, the compiler is actually just looking for methods with certain names, not specific interfaces or classes.

    The reason these features are not tied to specific interfaces is to decouple the language from the .NET framework implementation as much as possible. I suppose this would be considered a form of duck typing.

    Eric Lippert explains the feature and reasoning much more thoroughly here.

    I have noticed that the MSDN documentation is often wrong or incomplete about these features.

提交回复
热议问题