C# 中的匿名委托和通用列表
你能解释一下下面的代码吗:
private static List<Post> _Posts;
public static Post GetPost(Guid id)
{
return _Posts.Find(delegate(Post p)
{
return p.Id == id;
});
}
通过这种方式在通用列表中查找对象有什么意义? 他可以简单地迭代列表。
这个委托方法如何调用列表的每个元素?
注意:如果该问题有一个通用名称,您可以更新我的问题标题吗?
谢谢 !
Can you explain me code below :
private static List<Post> _Posts;
public static Post GetPost(Guid id)
{
return _Posts.Find(delegate(Post p)
{
return p.Id == id;
});
}
What is the point to find an object in a generic list by that way ? He can simply iterate the list.
How this delegated method called for each element of list ?
NOTE : if this has a common name, can you update my question's title ?
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你是对的,他可以迭代列表,你可以认为你的问题中的代码在概念上与以下内容相同:
它需要更少的代码来编写你的代码片段,重要的是你现在正在说出你想要找到的内容而不是确切地如何找到它:
在 C# 3.0 中,可以使用所谓的“lambda 表达式":
使用最少的可读代码来实现相同的目标,使该代码的编写者和读者都更满意。
You're quite right he can iterate over the list, you can think of the code in your question as being conceptually the same as the following:
It requires less code to write your snippet and importantly you are now saying what you want to be found and not exactly how to find it:
In C# 3.0 this can be shortened further using what is called a "lambda expression" to:
Using the least amount of readable code to achieve the same goal makes both writers and readers of that code happier.
他正在使用匿名代表。 他本可以使用 lambda 表达式 来代替:
此外,将访问包装为在这种情况下,方法中的列表不会实现任何目标,并将列表的元素公开给外部调用者。 这是不好的做法。
He is using an anonymous delegate. He could have used a lambda expression instead:
Also, wrapping access to the list in a method achieves nothing in this case and exposes the elements of the list to external callers. This is bad practice.
Predicate
返回 true。 它本质上是一个快捷方式,因此您不必遍历列表。List.Find(Predicate)
可能还具有一些内置优化。delegateInstance(arg1,arg2);
Predicate<T>
. It is essentially a shortcut so that you don't have to iterate over the list.List<T>.Find(Predicate<T>)
might also have some built-in optimizations.delegateInstance(arg1,arg2);
如果您使用的是 C# 3.0 或更高版本,则可以使用 Linq 在列表中快速查找对象。
If you are using C# 3.0 or later you can use Linq to find objects quickly in a List.
List.Find(Predicate match) 不是 LINQ 扩展方法,因为正如 MSDN 所示,该方法从 2.0 开始就已包含在框架中。
其次,使用Find()并没有什么问题。 它往往比其替代方案更具可读性:
经典:
LINQ:
使用 List.Find() 立即告诉您您正在查找一个项目,而其他项目则必须遵循逻辑来确定这一点。 Find() 基本上封装了列表项的迭代。 如果您在 Post 类上有一个类似
public bool HasId(Guid id)
的方法,那么您可以编写List.Find(Predicate match) is NOT a LINQ extension method, because this method has been in the framework since 2.0, as is indicated by MSDN.
Second, there is nothing wrong with using Find(). It tends to be more readable than its alternatives:
Classic:
LINQ:
Using List.Find() tells you immediately that you are look for an item, while the other you have to follow logic to ascertain this. Find() basically encapsulates the iteration over the list items. If you had a method on the Post class like
public bool HasId(Guid id)
then you could write