向第三方委托人签名添加参数

向第三方委托人签名添加参数

本文介绍了C#向第三方委托人签名添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个签名为"void Method(string)"的第三方代表.问题是我希望/需要将额外的附加信息传递给MySubscribedMethod(为简单起见,请说MyIntArg).我在订阅时就知道这些信息,但是显然我不允许更改MySubscribedMethod参数列表.

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?

推荐答案

这是为闭包设计的:

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

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

C#编译器将为您神奇地创建所有必要的基础结构,以确保在调用ThirdPartyDelegate时将myIntArg传递到MySubscribedMethod

The C# compiler will magically create all the necessary infrastructure for you to ensure that myIntArg is passed into MySubscribedMethod when ThirdPartyDelegate is invoked

(请注意,传递确切值的方式有很多细微差别,只有在您循环使用此值或在分配委托后更改myIntArg才真正重要;请参阅(如果您对血腥细节感兴趣)

(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)

这篇关于C#向第三方委托人签名添加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:32