How to turn if, else if logic into a ternary operator?

后端 未结 6 1818
执念已碎
执念已碎 2020-12-28 20:12

I was just wondering if this was possible because i started using ternary operators to reduce lines of code and i am loving it.

if (x==y)
{
    z += x;
} els         


        
6条回答
  •  被撕碎了的回忆
    2020-12-28 20:45

    To turn the z calculation into one line, I would do something like this:

    public int GetZBasedOnXY(int z, int x, int y)
    {
        // Chose this solution, but any can go in here and work.
        if (x == y || x == z)
            return z + y;
        else 
            return z + 1;
    }
    

    Then:

    z = GetZBasedOnXY(z, x, y);
    

    More readable, and if the naming is good and the method has unit test coverage, even better.

提交回复
热议问题