简体   繁体   中英

c# Conditional statement with |

Given:

bool isBold = true;
bool isItalic = true;
bool isStrikeout = false;
bool isUnderline = true;

System.Drawing.Font MyFont = new System.Drawing.Font(
    thisTempLabel.LabelFont,
    ((float)thisTempLabel.fontSize),
    FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline,
    GraphicsUnit.Pixel
);

How would I apply the boolean values to determine which font styles I should be using? The above code makes them all apply, so it's bold, italic, strikeout and underline, but I want to filter based on the bools.

Well, you could do this:

FontStyle style = 0; // No styles
if (isBold)
{
    style |= FontStyle.Bold;
}
if (isItalic)
{
    style |= FontStyle.Italic;
}
// etc

You could use:

FontStyle style = 0 | (isBold ? FontStyle.Bold : 0)
                    | (isItalic ? FontStyle.Italic : 0)
                    etc

but I'm not sure whether I would. It's a bit "tricksy". Note that both of these bits of code make use of the fact that the constant 0 is implicitly convertible to any enum type.

In addition to what Jon Skeet suggests, here's a fancier way with a Dictionary<,> . It's probably overkill for only four items, but maybe you will find the idea useful:

var map = new Dictionary<bool, FontStyle>
          {
             { isBold, FontStyle.Bold },
             { isItalic, FontStyle.Italic },
             { isStrikeout, FontStyle.Strikeout },
             { isUnderline, FontStyle.Underline }
          };

var style = map.Where(kvp => kvp.Key)
               .Aggregate(FontStyle.Regular, (styleSoFar, next) 
                                            => styleSoFar | next.Value);

What I like about it is the association between the flag and the associated style is cleanly separated from the 'bitwise gymnastics'.

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