ConvertAll(Guid.Parse) 如何工作?
首先我有这样的行
List<Guid> ratingComparisonIds = ratingComparison.ConvertAll<Guid>(o => Guid.Parse(o));
,然后 ReSharper 给了我一个提示,我可以将它转换为方法组。该操作的结果是这样的,
List<Guid> ratingComparisonIds = ratingComparison.ConvertAll<Guid>(Guid.Parse);
我对语法感到困惑..它是如何工作的以及为什么工作?我的意思是解析方法没有参数。我想说的是魔法。
更新
转换更加紧凑
List<Guid> ratingComparisonIds = ratingComparison.ConvertAll(Guid.Parse);
First I had this kind of line
List<Guid> ratingComparisonIds = ratingComparison.ConvertAll<Guid>(o => Guid.Parse(o));
Then ReSharper gave me a hint that I could convert it to method group. Result of that operation is this
List<Guid> ratingComparisonIds = ratingComparison.ConvertAll<Guid>(Guid.Parse);
I am confused about the syntax.. how and why does it work? I mean there is no parameters for the parse method. Magic I would say.
Update
Even more compact conversion
List<Guid> ratingComparisonIds = ratingComparison.ConvertAll(Guid.Parse);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它使用方法组转换。它正在做这样的事情:
现在内联变量,然后您就可以看到原始代码。这会让事情变得更清楚吗?
It's using a method group conversion. It's doing something like this:
Now inline the variable, and you get to the original code. Does that make things clearer?
ConvertAll
(在此上下文中)需要一个Converter
- 一个接受string
并返回一个方法的委托指南
。静态Guid.Parse
完美满足这一点 - 与我们编写new Converter(Guid.Parse)
完全相同,或写为:lambda 版本通过匿名方法添加了一定程度的间接:
因此直接调用
Guid.Parse
实际上稍微高效的。ConvertAll
(in this context) takes here requires aConverter<string,Guid>
- a delegate to a method that takes astring
and returns aGuid
. The staticGuid.Parse
satisfies that perfectly - exactly the same as if we had writtennew Converter<string,Guid>(Guid.Parse)
, or written:The lambda version adds a level of indirection via an anonymous method:
so the direct call to
Guid.Parse
is actually marginally more efficient.