可以使用预定义参数将方法附加到委托吗?

有时我会遇到需要将方法附加到委托但签名不匹配的情况,例如尝试将abc附加到somedelegate,字符串参数为“hi”。

public class test { //... public void abc(int i, string x) { //Do Something } //... } public class test2 { somedelegate x; //... public test2() { //Do Something test y = new test(); x += y.abc(,"hi"); } delegate void somedelegate(int i); } 

我可以通过创建具有正确签名的另一个委托然后附加它来解决它,但它似乎不必要地复杂。 你能用C#做这样的事吗? 谢谢。

对。 我想我没有办法按照我的设想去做,但我仍然可以像x + =(int i)=> abc(i,“hi”);那样做。 所以现在没问题,谢谢你们。

是的,你可以用闭包来做到这一点

[在msdn上对这个主题进行了很好的处理,但就像其他任何东西一样很难找到]

大图

  • 编写一个可以获取所需参数的方法
  • 在该方法中,您将返回一个匿名方法,该方法具有所需的委托 – 目标签名
  • 此方法的调用本身是委托实例化中的参数

是的,这有点像Matrix-y。 但方式很酷。

 delegate void somedelegate (int i); protected somedelegate DelegateSignatureAdapter ( string b, bool yesOrNo, ...) { // the parameters are local to this method, so we'll go w/ that. // our target delegate requires a single int parameter and void return return (int a) => { // your custom code here // all calling arguements are in scope - use them as needed }; // don't forget the semicolon! } // our delegate call somedelegate myWarpedDelegate = new somedelegate (DelegateSignatureAdapter("someString", true)); myWarpedDelegate (2543); myWarpedDelegate(15); 

只需谷歌搜索’.net委托可选参数’返回一些可能有用的结果:

  • 委托可以有一个可选参数吗?
  • VB.NET – 有没有办法在委托中使用可选参数? (或计划允许这个?)
  • 可选参数和代理

更新(进一步研究,并通过上面的第一个链接帮助):

你可以使用Invoke方法,它接受任何委托吗?