c#带条件语句|

时间:2011-03-18 10:38:33

标签: c# fonts if-statement operators

假设:

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
);

我如何应用布尔值来确定我应该使用哪种字体样式?上面的代码使它们全部适用,所以它是粗体,斜体,删除线和下划线,但我想基于bools进行过滤。

2 个答案:

答案 0 :(得分:9)

嗯,你可以这样做:

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

可以使用:

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

但我不确定我是否愿意。这有点“狡猾”。请注意,这两个代码都使用了常量0可以隐式转换为任何枚举类型的事实。

答案 1 :(得分:2)

除了Jon Skeet所建议的内容之外,这里还有一个Dictionary<,>的方式。只有四件物品可能有点过头了,但也许你会发现这个想法很有用:

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);

我喜欢的是旗帜和相关风格之间的联系与“按位体操”完全分开。