我昨天遇到这种情况,它一直在咬我。编译器在调用Action(据我理解是具有“ void”返回类型的委托)时,不会抱怨为DoThis方法使用对函数的引用。
DoThis函数上此Action参数的实际作用是什么?
public class testit
{
// Call DoThis with just a function reference. Should not work, but does.
public void DoThisThing1() {
DoThis(this.thing1);
}
// Call DoThis with an action. This is correct.
public void DoThisThing2() {
DoThis(new Action<string, string>(this.thing2));
}
private void DoThis(Action<string, string> thing)
{
// Do some common things here.
// Invoke Action
thing.Invoke("1", "2");
// Do other things.
}
private void thing1(string p1, string p2){}
private void thing2(string p1, string p2){}
}
如果您的问题是为什么这样做有效:
DoThis(this.thing1);
然后隐式地:
DoThis(new Action<string,string>(this.thing1));
(其中的委托类型是根据的已解析方法签名来推断的DoThis
)
简单来说:编译器为我们填充了一些东西-自C#2起就存在的语法糖。在C#1.1中,它不会进行编译。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句