C# - 谁能告诉我,为什么和我应该在哪里使用委托? [英] C# - Can someone tell me why and where I should use delegates?

查看:176
本文介绍了C# - 谁能告诉我,为什么和我应该在哪里使用委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我明白在C#中的委托作为指针的方法的概念,但我不能找到的地方是使用他们一个好主意任何很好的例子。什么是一些例子,或者是显著更优雅/更好地与代表或不能使用其他方法来解决?

I think I understand the concept of a delegate in C# as a pointer to a method, but I cant find any good examples of where it would be a good idea to use them. What are some examples that are either significantly more elegant/better with delegates or cant be solved using other methods?

推荐答案

究竟你代表是什么意思?以下是他们可以采用两种方式:

What exactly do you mean by delegates? Here are two ways in which they can be used:

void Foo(Func<int, string> f) {
 //do stuff
 string s = f(42);
 // do more stuff
}

void Bar() {
 Func<int, string> f = delegate(i) { return i.ToString(); } 
//do stuff
 string s = f(42);
 // do more stuff
}

在第二个点是你可以声明动态新的功能,如代表。这可以通过lambda表达式在很大程度上取代,并且是非常有用的,你有一小块要1逻辑中的任何时间)传递给另一个功能,或2)只执行重复。 LINQ是一个很好的例子。每个LINQ功能需要一个lambda表达式作为其参数,指定的行为。例如,如果你有一个列表与LT; INT> →然后 l.Select(X =方式>(x.ToString())将调用toString()列表中的每一个元素上lambda表达式我写的是作为一个代表。

The point in the second one is that you can declare new functions on the fly, as delegates. This can be largely replaced by lambda expressions,and is useful any time you have a small piece of logic you want to 1) pass to another function, or 2) just execute repeatedly. LINQ is a good example. Every LINQ function takes a lambda expression as its argument, specifying the behavior. For example, if you have a List<int> l then l.Select(x=>(x.ToString()) will call ToString() on every element in the list. And the lambda expression I wrote is implemented as a delegate.

第一个案例说明了如何选择可能会实现。你把一个委托作为你的论点,然后调用它的时候必要的。这就允许调用自定义函数的行为。考虑选择()作为一个例子再次,本身的功能保证您传递给它的代表将列表中的每一个元素上调用,每个的输出将被退回。这也就代表实际的确实的是给你。这使得它一个令人惊讶的灵活性和通用功能。

The first case shows how Select might be implemented. You take a delegate as your argument, and then you call it when needed. This allows the caller to customize the behavior of the function. Taking Select() as an example again, the function itself guarantees that the delegate you pass to it will be called on every element in the list, and the output of each will be returned. What that delegate actually does is up to you. That makes it an amazingly flexible and general function.

当然,他们再还用于订阅事件。简单地说,代表们允许你引用功能,采用它们作为函数调用的参数,将它们分配给变量和其他任何你喜欢做的事。

Of course, they're also used for subscribing to events. In a nutshell, delegates allow you to reference functions, using them as argument in function calls, assigning them to variables and whatever else you like to do.

这篇关于C# - 谁能告诉我,为什么和我应该在哪里使用委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆