简体   繁体   中英

C#, "?" and ":" operators

I not found any solution for my problem so i ask, how ? and : operators works when i have multiple statemants?

What i want to do, i have pixel on the middle pixel[pos] and pixels around, its look like:

0 0 0
0 x 0
0 0 0

x is a center pixel.

Im checking, if i have any white ( zero ) pixel around it. If is anyone, i marked pixel as two . If not, so pattern looks like:

1 1 1
1 x 1
1 1 1

1 is an black pixel, i set it to one .

Now, the code:

if(pixels[positionOfPixel] == one && x > 0 && x < width 
                                  && y > 0 && y < height)
{
    pixels[positionOfPixel] = pixels[positionOfPixel - 1]          == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel + 1]          == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset]     == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel + offset]     == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset + 1] == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel + offset - 1] == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset - 1] == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset + 1] == zero ? two : zero;
}

My question is, why every one pixel is marked as two ? Why it didnt recognize pixel, where every pixel arond is one (like in second pattern)?

Thanks for any advices!

I'm not a C# specialist, but there is common rule how ? : operator can be used.

x = (boolean condition) ? reult_if_true : result_if_false;

Eg

drink = isThisPersonAGirl ? wine : beer;

If you want to use many conditions with ? : operator, you should do it that way:

x = (boolean condition 1) ? result_if_true : (boolean condition 2) ? result_if_bool_2_is_true : result_if false;

Eg

drink = isThisPersonAChild ? lemonade : isThisPersonAGitl ? wine : beer

In your code snippet, it's hard to understand what's going on because you use = operator too often. In most languages, you could initalize several variables like this:

a = b = c = 0, so a, b, c will be = 0;

So I think your mistake is using = operator too often so maybe only this condition does matter, while others are simply skipped:

pixels[positionOfPixel - offset + 1] == zero ? two : zero;

Sorry of it doesn't help, since I'm really not a C# coder)

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