可以将方法附加到具有预定义参数的委托吗?

Can a method be attached to a delegate with predefined parameters?(可以将方法附加到具有预定义参数的委托吗?)
本文介绍了可以将方法附加到具有预定义参数的委托吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会遇到必须将方法附加到委托但签名不匹配的情况,例如尝试将 abc 附加到某个字符串参数为hi"的委托.

Sometimes I encounter cases where I have to attach a method to a delegate but the signature doesn't match, like trying to attach abc down there to somedelegate with the string parameter being "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# 中做这样的事情吗?谢谢.

I can work it around by creating another delegate with the correct signature then attaching it but it seems so unnecessarily complex. Can you do something like this in C#? Thanks.

我想最接近我想要实现的是:

I guess there closest to what I wanted to achieve is:

x += (int i) => abc(i, "hi");

推荐答案

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

[在 msdn 上有一个很好的主题处理,但就像那里的其他内容一样,很难找到]

[there's a nice treatment of the subject on msdn, but like anything else in there it's hard to find]

大局

  • 编写一个可以接受所有你需要的参数的方法
  • 在该方法中,您返回一个匿名方法,该方法具有所需的委托目标签名
  • 这个方法的调用本身就是委托实例化中的参数
  • Write a method that can take all the parameters you need
  • Inside that method you return an anonymous method with the delegate-target signature it requires
  • This method's call is itself the parameter in the delegate instantiation

是的,这有点像 Matrix-y.但是很酷.

Yes, this is a bit Matrix-y. But way cool.

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

这篇关于可以将方法附加到具有预定义参数的委托吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)