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

前端 未结 2 1635
故里飘歌
故里飘歌 2020-12-21 09:14

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 str

相关标签:
2条回答
  • 2020-12-21 10:19

    Just Googling for '.net delegate optional parameters' returns some results that may be useful:

    • Can a Delegate have an optional parameter?
    • VB.NET - Is there a way to utilize optional parameters in delegates? (Or Plans to Allow this?)
    • Optional Parameters and Delegates

    Update (researching this some more, and helped by the first link above):

    Could you perhaps use the Invoke method, which accepts any delegate?

    0 讨论(0)
  • 2020-12-21 10:20

    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);
    
    0 讨论(0)
提交回复
热议问题