问题描述
有时我会遇到必须将方法附加到委托但签名不匹配的情况,例如尝试将 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);
这篇关于可以将方法附加到具有预定义参数的委托吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!