问题
I have a 3rd party delegate with a "void Method (string)" signature. The problem is I want/need to pass extra additional information to MySubscribedMethod (Lets say MyIntArg for simplicity). I know this information at the time of the subscription, but I obviously not allowed to alter the MySubscribedMethod parameter list.
ThirdPartyClass.ThirdPartyDelagate += MySubscribedMethod; // Want to provide MyIntArg
public void MySubscribedMethod(string Arg) {} // Would like to receive MyIntArg
Does anyone know an elegant work around for this type of issue?
Thanks,
回答1:
This is what closures were designed for:
int myIntArg = whatever;
ThirdPartyClass.ThirdPartyDelagate += s => MySubscribedMethod(s, myIntArg);
public void MySubscribedMethod(string Arg, int intArg) {}
The C# compiler will magically create all the necessary infrastructure for you to ensure that myIntArg
is passed into MySubscribedMethod
when ThirdPartyDelegate
is invoked
(note there are various subtlies around what exact value gets passed in that only really matter if you're using this in a loop or changing myIntArg
after you've assigned the delegate; see this if you're interested in the gory details)
来源:https://stackoverflow.com/questions/7842234/c-sharp-adding-arguments-to-a-3rd-party-delagate-signature