问题描述
当分支选择一个函数时,使用三元运算符来选择一个函数可能是有意义的,但这是不可能的.为什么?
When branching to select a function, it might make sense to use the ternary operator to select a function, but this is impossible. Why?
public class Demo {
protected bool branch;
protected void demo1 () {}
protected void demo2 () {}
public Action DoesntWork() {
return branch ? demo1 : demo2;
}
}
编译器产生以下错误:
Cannot implicitly convert type `method group' to `System.Action'
推荐答案
问题是demo1
不是一个简单的表达式,它是一个方法.并且方法可以被覆盖,所以它实际上不是一个方法,它是一个方法组.考虑以下示例:
The problem is that demo1
is not a simple expression, it is a method. And methods can be overriden, so it is not actually one method, it is a method group. Consider the following example:
public class Demo {
protected bool branch;
protected void demo1 (int) {}
protected void demo1 () {}
protected void demo2 () {}
public Action DoesntWork() {
return branch ? demo1 : demo2; //Error
return demo1; //ok
}
}
现在,demo1
被重载了,那么这两个版本应该使用哪一个呢?答案是通过使用函数的上下文来选择重载函数.
Now, demo1
is overloaded, so which one of the two versions should be used? The answer is that the overloaded function is selected by using the context in which the function is used.
在 return demo1
中很明显,它需要一个 Action
.
In the return demo1
it is obvious, it expects an Action
.
但是在 return 分支中呢?demo1 : demo2;
上下文并不那么容易.三元运算符首先尝试将 demo1
的类型与 demo2
的类型进行匹配,但那是另一个 方法组,因此没有任何帮助.编译器没有超越并失败.
But in the return branch? demo1 : demo2;
the context is not so easy. The ternary operator first tries to match the type of demo1
with that of demo2
, but that is another method group so there is no help there. The compiler does not look beyond and fails.
解决方案是明确方法组的预期类型:
The solution is to make clear the type expected from the method group:
return branch? new Action(demo1) : demo2;
return branch? (Action)demo1 : demo2;
Action d1 = demo1;
return branch? d1 : demo2;
这篇关于为什么 C# 三元运算符不能与委托一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!