是否三元":?运营商QUOT;在C#中的错误? [英] Does the ternary "?: operator" have a bug in C#?

查看:156
本文介绍了是否三元":?运营商QUOT;在C#中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能运行下面的代码

Why can not I run the following code ?

    static int num = 0;
    static void Main(string[] args)
    {
        (num == 0) ? inc() : dec();
    }
    public static void inc()
    {
        num++; 
    }
    public static void dec()
    {
        num--;
    }



为什么不C#允许我使用三元?:操作符检查的条件,然后相应地运行的方法,而不需要返回任何值?等价于这样的:

Why doesn't C# allow me to use the ternary "?:" operator to check a condition and then run a method accordingly without the need to return any value? Equivalently to this:

            if (num == 0) inc();
            else dec();

如果在其他语言中应用了相同的规则,我不知道如JAVA,C ++等...

I am not sure if the same rule is applied in other languages, e.g., Java, C++, etc...

推荐答案

乔恩斯基特的回答是完全记录,C#语言故意去比C不同的路线++。这是很难说的为什么的,但我会努力,因为我认为,这个问题值得一个答案了。

Jon Skeet's answer is perfectly documenting that C# intentionally went a different route than C++. It is difficult to say why, but I will try because I believe that that question deserves an answer, too.

C#股票很多语法C ++和与Java。在这种情况下,被选为Java的方式。这涉及两个无法写 2 + 2; 作为一个独立的声明,以及要求三元运算符返回一个值

C# shares a lot of syntax with C++ and with Java. In this case, the Java way was chosen. This concerns both the inability to write 2 + 2; as a standalone statement, as well as requiring that ternary operator returns a value.

我相信,这两个决定有很多事情要做消除无法访问代码。在 + 运营商 2 + 2 可以被优化掉,因此,如果它所服务代码中的任何目的,这个目的是不可靠服了!静态分析(编译错误或警告)最好应该告诉你,有似乎是在这种情况下,一个语义问题,并迫使你删除或重写不可访问的代码。

I believe that both of these decisions have a lot to do with elimination of inaccessible code. The + operator in 2 + 2 can be optimized away and therefore if it serves any purpose in the code, that purpose is unreliably served! Static analysis (compilation error or warning) should ideally tell you that there seems to be a semantic problem in such a case and force you to delete or rewrite the inaccessible code.

所以,表情也不再总是语句,以及C语法需要被重新定义的Java / C#中,有表情总是返回值和声明从来没有返回值。

So, expressions are no longer always statements, and the C grammar needs to be redefined for Java/C#, with expressions always returning values and statements never returning values.

现在如果 - 其他在一个作为一个主要区别表达和一个是陈述的,至少在它们的典型用途。因此,重新定义的语法简单地选择禁止无效ternaries和建议如果 - 其他用于这一目的。

Now ?: and if-else differ primarily in one being an expression and one being a statement, at least in their typical uses. So the redefined grammar simply chose to ban void ternaries and recommend if-else for that purpose.

这篇关于是否三元":?运营商QUOT;在C#中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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