C# 将参数添加到第 3 方委托签名

发布于 2024-12-10 19:31:35 字数 370 浏览 0 评论 0原文

我有一个带有“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

街道布景 2024-12-17 19:31:35

这就是闭包的设计目的:

int myIntArg = whatever;
ThirdPartyClass.ThirdPartyDelagate += s => MySubscribedMethod(s, myIntArg);

public void MySubscribedMethod(string Arg, int intArg) {}

C# 编译器会神奇地为您创建所有必要的基础设施,以确保在 ThirdPartyDelegate 时将 myIntArg 传递到 MySubscribedMethod 中。 > 被调用

(请注意,关于传入的确切值存在各种微妙之处,只有当您在循环中使用它或在分配委托后更改 myIntArg 时,这些微妙之处才真正重要;请参阅,如果您对血淋淋的细节感兴趣)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文