【问题标题】:c# Conditional statement with |c# 条件语句 with |
【发布时间】:2011-07-18 01:43:21
【问题描述】:

给定:

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

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

【问题讨论】:

    标签: c# fonts if-statement operators


    【解决方案1】:

    好吧,你可以这样做:

    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 可以隐式转换为任何枚举类型这一事实。

    【讨论】:

    • 谢谢!刚刚了解枚举,这对我来说现在更有意义了。
    • @TheSean:是的,只是一个错字:(
    【解决方案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);
    

    我喜欢它的地方在于标志和相关样式之间的关联与“按位体操”完全分开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2017-04-18
      • 2019-04-12
      • 1970-01-01
      相关资源
      最近更新 更多