为什么不与代表的C#三元运算符的工作? [英] Why doesn't the C# ternary operator work with delegates?

查看:167
本文介绍了为什么不与代表的C#三元运算符的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当分支选择功能,它可能是有意义的使用三元运算选择功能,但这是不可能的。为什么

 公共类演示{
保护布尔支?;
保护无效demo1的(){}
保护无效DEMO2(){}
公益行动DoesntWork(){
返回分支? demo1的:DEMO2;
}
}



编译器生成以下错误:



 无法隐式转换类型`方法组'到`System.Action'


解决方案

的问题是, demo1的不是一个简单的表情,那是一种的方法的。和方法可以被覆盖,所以它实际上没有有一个的方法,它是一个的方法组的。请看下面的例子:

 公共类演示{
保护布尔分支;
保护无效demo1的(INT){}
保护无效demo1的(){}
保护无效DEMO2(){}
公益行动DoesntWork(){
返回分支? demo1的:DEMO2; //错误
返回demo1的; // OK
}
}

现在, demo1的超载,所以在两个版本中的哪一个应该使用?答案是重载功能是通过使用其中使用的功能的上下文中选择。



收益demo1的这是显而易见的,它需要一个动作



而在返回分支? demo1的:DEMO2; 的背景也不是那么容易。三元运算符先尝试与 DEMO2 匹配 demo1的的类型,但那是另一个的方法组的所以没有帮助那里。该编译器不会超越和失败



解决方案是明确从方法组期望的类型:

 返回分支?新的Action(demo1的):DEMO2; 

返回分支? (动作)demo1的:DEMO2;

行动D1 = demo1的;
返回分支? D1:DEMO2;


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

The compiler produces the following error:

Cannot implicitly convert type `method group' to `System.Action'

解决方案

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
    }
}

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.

In the return demo1 it is obvious, it expects an Action.

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#三元运算符的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆