开发者

c# Conditional statement with |

开发者 https://www.devze.com 2023-02-18 18:21 出处:网络
Given: bool isBold = true; bool isItalic = true; bool isStrikeout = false; bool isUnderline = true; System.Drawing.Font MyFont = new System.Drawing.Font(

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开发者_Go百科 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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消