简体   繁体   中英

If Then Else Shorthand Won't Work Without Assignment

In C#, I am trying to shorten some of my return code. What I want to do is something like

condition ? return here:return there;

or

condition ?? return here;

I am having some issues though, the compiler says the expression is not valid. Here is an example:

        int i = 1;
        int a = 2;
        i < a ? i++ : a++;

This is not valid. However,

        int i = 1;
        int a = 2;
        int s = i < a ? i++ : a++;

is valid. Must there be assignment to use this shorthand notation? The only way I can think of using this at the moment is:

int acceptReturn = boolCondition ? return toThisPlace() : 0 ;

I would really like that line of code to look more like:

boolCondition ? return toThisPlace():;

Which is not valid but is what I am after.

? : is not "shorthand" for if/else - it is a specific operator (conditional) with specific semantic rules. Those rules mean it can be used only as an expression, not as a statement.

Re the return: if you only want to "return if true", then code it as such:

if(condition) return [result];

Don't try and use a conditional operator as something it is not.

您需要将返回移到三元操作之外。

return boolCondition ? toThisPlace() : 0 ; 

You've got your statement out of order.

Instead of

condition ? return here:return there;

which, as you have found, doesn't compile, do

return condition ? here: there;

No, that's impossible. return is a statement; it cannot be part of an expression, which is what ?: , the ternary operator (not logic control statement), expects in all three of its operands. You'll have to use the usual form. Don't worry though, this is a good thing - it'll make your code more readable in the long run.

The ternary operator ?: is limited in C#. What you could do in this case is:

return condition ? here : there;

你需要这样写你的陈述

return condition ? here : there;

The answers are (depending on your C# version and needs):

return condition ? here : there;
return here ?? there; // if you want there when here is null

return boolCondition ? toThisPlace() : default;
return boolCondition ? toThisPlace() : default(int);
return boolCondition ? toThisPlace() : 0;

Now you can assign the result to the underscore '_' variable that will be ignored:

_ = i < a ? i++ : a++;

It's the best I can think of if you really want to avoid if, else, and the brackets that, in some teams, are mandatory to use with every if like this:

if (i < a)
{
    i++;
}
else
{
    a++;
}

The return in your example will be:

_ = boolCondition = return toThisPlace() : default; // this is horrible, don't do it

您的代码没问题,唯一的问题是您正在读取条件上的 i 变量,同时您正在尝试更改变量的值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM