C# - Can someone tell me why and where I should us

2019-01-22 15:38发布

This question already has an answer here:

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?

标签: c# delegates
12条回答
The star\"
2楼-- · 2019-01-22 16:26

One of the benefits of Delegates is in asynchronous execution.

when you call a method asynchronously you do not know when it will finish executing, so you need to pass a delegate to that method that point to another method that will be called when the first method has completed execution. In the second method you can write some code that inform you the execution has completed.

查看更多
爷、活的狠高调
3楼-- · 2019-01-22 16:29

Some other comments touched on the async world... but I'll comment anyway since my favorite 'flavor' of doing such has been mentioned:

ThreadPool.QueueUserWorkItem(delegate
{
    // This code will run on it's own thread!
});

Also, a huge reason for delegates is for "CallBacks". Let's say I make a bit of functionality (asynchronously), and you want me to call some method (let's say "AlertWhenDone")... you could pass in a "delegate" to your method as follows:

TimmysSpecialClass.DoSomethingCool(this.AlertWhenDone);
查看更多
欢心
4楼-- · 2019-01-22 16:31

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
}

and

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

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.

查看更多
Rolldiameter
5楼-- · 2019-01-22 16:35

Is there an advantage to use a delegate when dealing with external calls to a database?

For example can code A :

static void Main(string[] args) {

           DatabaseCode("test");

}

public void DatabaseCode(string arg) {

           .... code here ...

}

Be improved in code B :

static void Main(string[] args) {

           DatabaseCodeDelegate slave = DatabaseCode;
           slave ("test");

}

public void DatabaseCode(string arg) {

           .... code here ...

}
public delegate void DatabaseCodeDelegate(string arg);

It seems that this is subjective, but an area where there are strong conflicting view points?

查看更多
唯我独甜
6楼-- · 2019-01-22 16:36

I primarily use the for easy asynch programming. Kicking off a method using a delegates Begin... method is really easy if you want to fire and forget.

A delegate can also be used like an interface when interfaces are not available. E.g. calling methods from COM classes, external .Net classes etc.

查看更多
ら.Afraid
7楼-- · 2019-01-22 16:39

For example in multithread apps. If you want several threads to use some control, You shoul use delegates. Sorry, the code is in VisualBasic.

First you declare a delegate

Private Delegate Sub ButtonInvoke(ByVal enabled As Boolean)

Write a function to enable/disable button from several threads

Private Sub enable_button(ByVal enabled As Boolean)
    If Me.ButtonConnect.InvokeRequired Then

        Dim del As New ButtonInvoke(AddressOf enable_button)
        Me.ButtonConnect.Invoke(del, New Object() {enabled})
    Else
        ButtonConnect.Enabled = enabled
    End If

End Sub
查看更多
登录 后发表回答