Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method be attached to a delegate with predefined parameters?

Sometimes I encounter cases where I have to attach a method to a delegate but the signature doesn't match, like trying to attach abc down there to somedelegate with the string parameter being "hi".

public class test
{
   //...
   public void abc(int i, string x)
   {
      //Do Something
   }
   //...
}
public class test2
{
   somedelegate x;
   //...
   public test2()
   {
      //Do Something
      test y = new test();
      x += y.abc(,"hi");
   }
   delegate void somedelegate(int i);
}

I can work it around by creating another delegate with the correct signature then attaching it but it seems so unnecessarily complex. Can you do something like this in C#? Thanks.

EDIT: I guess there closest to what I wanted to achieve is:

x += (int i) => abc(i, "hi");
like image 487
resgh Avatar asked Nov 24 '25 14:11

resgh


1 Answers

Yes, you can do this with closures

[there's a nice treatment of the subject on msdn, but like anything else in there it's hard to find]

The Big Picture

  • Write a method that can take all the parameters you need
  • Inside that method you return an anonymous method with the delegate-target signature it requires
  • This method's call is itself the parameter in the delegate instantiation

Yes, this is a bit Matrix-y. But way cool.

delegate void somedelegate (int i);

protected somedelegate DelegateSignatureAdapter ( string b, bool yesOrNo, ...) {
    // the parameters are local to this method, so we'll go w/ that.

    // our target delegate requires a single int parameter and void return
    return  (int a) => {
                // your custom code here
                // all calling arguements are in scope - use them as needed

    };  // don't forget the semicolon!
}

// our delegate call
somedelegate myWarpedDelegate = new somedelegate (DelegateSignatureAdapter("someString", true));
myWarpedDelegate (2543);
myWarpedDelegate(15);
like image 137
radarbob Avatar answered Nov 26 '25 04:11

radarbob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!