C# 将参数添加到第 3 方委托签名
我有一个带有“void Method(string)”签名的第三方委托。 问题是我想要/需要将额外的附加信息传递给 MySubscribedMethod (为了简单起见,让我们说 MyIntArg )。我在订阅时知道这些信息,但显然不允许更改 MySubscribedMethod 参数列表。
ThirdPartyClass.ThirdPartyDelagate += MySubscribedMethod; // Want to provide MyIntArg
public void MySubscribedMethod(string Arg) {} // Would like to receive MyIntArg
有谁知道解决此类问题的优雅方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是闭包的设计目的:
C# 编译器会神奇地为您创建所有必要的基础设施,以确保在
ThirdPartyDelegate
时将myIntArg
传递到MySubscribedMethod
中。 > 被调用(请注意,关于传入的确切值存在各种微妙之处,只有当您在循环中使用它或在分配委托后更改
myIntArg
时,这些微妙之处才真正重要;请参阅此,如果您对血淋淋的细节感兴趣)This is what closures were designed for:
The C# compiler will magically create all the necessary infrastructure for you to ensure that
myIntArg
is passed intoMySubscribedMethod
whenThirdPartyDelegate
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)