为什么 Func<> 的这个 MSDN 示例是这样的?委托有多余的 Select() 调用吗?
MSDN 在 Func 通用委托:
Func<String, int, bool> predicate = ( str, index) => str.Length == index;
String[] words = { "orange", "apple", "Article", "elephant", "star", "and" };
IEnumerable<String> aWords = words.Where(predicate).Select(str => str);
foreach (String word in aWords)
Console.WriteLine(word);
我了解所有内容这是在做。我不明白的是
Select(str => str)
一点。这肯定不需要吧?如果你把它省略掉,
IEnumerable<String> aWords = words.Where(predicate);
然后你仍然会得到一个包含相同结果的 IEnumerable 返回,并且代码打印相同的内容。
我错过了什么,或者这个例子有误导性吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Select
确实是多余的。我怀疑这个例子可能是从查询理解语法“翻译”而来的,如下所示:
当使用此语法时,您必须在最后
选择
,这就是如何编译器工作了。但是,当使用Where
扩展方法时,完全没有必要,除非您确实需要进行单独的投影。或者,也许这只是一个错误。 MSDN 作者并非绝对正确!
The
Select
is indeed redundant.I suspect that this example may have been "translated" from the query comprehension syntax, as in:
When using this syntax, you have to
select
at the end, it's just how the compiler works. When using theWhere
extension method, however, it's completely unnecessary unless you actually need to do a separate projection.Or, maybe it's just a mistake. The MSDN writers aren't infallible!
不,不需要。
如果您想强制延迟评估序列(即防止强制转换),则可以使用此类构造。如果您有一个返回
List
的方法,但声明了IEnumerable
返回类型,则客户端可以强制转换返回类型并直接操作底层列表。显然这是一个非常糟糕的主意,但是类可以通过应用身份选择来保护其状态,例如本示例中使用的选择:No it's not needed.
Such a construct could be used if you wanted to force a sequence to be lazily evaluated i.e. to prevent casting. If you had a method that returned a
List<T>
but declared anIEnumerable<T>
return type then a client could cast the return type and manipulate the underlying list directly. Obviously this is a very bad idea, but a class could protect its state by applying an identity select such as the one used in this example:事实上,这是不需要的,msdn 页面。告诉他们不需要 .Select。 Select 子句的事实只是:
它接收字符串并输出相同字符串
Indeed, it's not needed, there's a feedback button on bottom of msdn page. Tell them the .Select is not needed. The mere fact that the Select clause is just:
It receives string and outputs the same string
你那里有一个非常奇怪的链接。该主题不在目录中,并且顶部有以下内容:
“[该主题是预发行文档,在未来版本中可能会发生更改。空白主题作为占位符包含在内。]”
第一行看起来也像是作者对自己的评论。
而且自从 VS 2010 和 .NET 4.0 刚刚发布以来,我想,这是某种没有及时删除/替换的损坏主题。
我认为,现在此内容的正确 URL 是这样的: http://msdn .microsoft.com/en-us/library/bb534303.aspx
顺便问一下,您是如何获取 URL 的?是通过MSDN搜索还是其他什么方式?
You have a very strange link there. This topic is not in TOC, and it has the following at the top:
"[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]"
The first line also looks like writer's comment to himself/herself.
And since VS 2010 and .NET 4.0 just released, I guess, this is some kind of broken topic that hasn't been deleted/replaced in time.
I think, the correct URL now for this content is this: http://msdn.microsoft.com/en-us/library/bb534303.aspx
By the way, how did you get your URL? Was it through MSDN search or something else?