C# Adding arguments to a 3rd party delagate signature

五迷三道 提交于 2019-12-13 01:14:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!