开发者

What’s the advantage of using a delegate over making an intermediary method?

开发者 https://www.devze.com 2023-04-12 07:35 出处:网络
Is there a reason to use this: bool flag; public Form1() { if (flag) byDelegate = square; else byDelegate = cube;

Is there a reason to use this:

bool flag;

public Form1()
{
    if (flag) byDelegate = square;
    else byDelegate = cube;
    Text = byDelegate(3).ToString();          
}

int squa开发者_高级运维re(int i) { return i * i; }
int cube(int i) { return i * i * i; }

delegate int delegate1(int x);
delegate1 byDelegate;

Rather than:

bool flag;

public Form2()
{
    Text = fakeDelegate(3).ToString(); 
}

int square(int i) { return i * i; }
int cube(int i) { return i * i * i; }

int fakeDelegate(int i)
{
    if (flag) return square(i);
    else return cube(i);
}

Thanks.


Delegates are usually used asynchronously, for events or passed into methods/types so that the method the delegate points to ('function pointers') can be called later. In your case there looks like there's no advantage as you're doing everything synchronously.

For example

private Action<double> _performWhenFinished.

public Form1(Action<double> performWhenFinished)
{
    _performWhenFinished = performWhenFinished;        
}

public void CalculatePi()
{
   double pie = 0d;
    // Create a new thread, take 2 minutes to perform the task

    // Thread.Wait etc., then and run your delegate 
    _performWhenFinished(pie);
}

You generally don't need to declare your own delegates in 3.5 upwards unless you want to your code to provide a bit more meaning via those declarations. The Action type and the Func type (func provides a method with a return value) save you the effort.


To address the precise situation you mentioned, you'll be over-complicating things by explicitly using a delegate, and even more if you don't really understand what's going on behind the scenes (I'm not saying you don't)...

More generally, you can think of a delegate as a "contract" (or as a "pointer to a function" if your background is in C/C++): you are telling the compiler to expect in that place a function receiving a given list of parameters and providing a given output (possibly void), but you don't tell it what the function really does. That "decouples" the method's body from the real implementation of the function, giving you the freedom to pass several different implementations from different parts of your code.

There seem to be pretty good, more elaborated explanations at this topic.


In the situation you describe I don't see any advantage to using delegates. Quite the opposite in fact since it if nothing else makes things look more complicated.

The reason to use delegates would be for example if you want to allow outside code to specify the function to call and if you don't know in advance all the functions that may be specified.


fakeDelegate is not a delegate at all: it is just a method call (that in turn calls one of two other methods).

Now, two reasons where delegates -- including lambdas and "anonymous functions" -- are very useful are:

  1. Delegates allow a function (or method) to treated as a first-class value. The first example in the post does this, even though it is a silly example (I do this sometimes, but a larger context would be required to argue the validity of one form over the other). More often, I use this property for a data-structure that looks like IDictionary<String,MyDelegate> which is then used as map["foo"](bar) or similar -- can't do this without a big ugly dispatch (or reflection) without first-class functions values!

  2. A /new/ delegate can create a closure -- that is, it can bind over free variables in the current lexical scope. This cannot be done with normal methods; neither cube nor square will create a closure, even though the method group is convertible to a delegate. While there is no advantage in the example above, this can be very handy when "just needing to pass that extra little bit of information" to a callback.

Since neither of these two cases are (particularly well) used in the example then....

Happy coding.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号