代码之家  ›  专栏  ›  技术社区  ›  Shaiju T

将多个if语句转换为短语句

  •  0
  • Shaiju T  · 技术社区  · 6 年前

    我想用逗号分隔 string 基于 boolean 中的属性值 model .

    代码

            string options = string.Empty;
    
            if (model.Fruits.Value)
            {
                options += "FR,";
            }
            if (model.Drinks.Value)
            {
                options += "DR,";
            }
            if (model.Lunch.Value)
            {
                options += "LU,";
            }
            if (model.Dinner.Value)
            {
                options += "DI,";
            }
    

    我们能把上面的代码简写下来吗? ternary conditional operator (?:) 或者我应该保留上面的那个,因为它更可读?

    任何建议都很好。

    2 回复  |  直到 6 年前
        1
  •  5
  •   Marc Gravell    6 年前

    可能有 一些 这种方法的优点如下:

        string options = 
            (model.Fruits.Value ? "FR," : "")
            + (model.Drinks.Value ? "DR," : "")
            + (model.Lunch.Value ? "LU," : "")
            + (model.Dinner.Value ? "DI," : "");
    

    具体来说,这将是 string.Concat (见 example here -你在找单曲 call string [mscorlib]System.String::Concat(string, string, string, string) ,这样就避免了大量中间字符串( += )在“所有选项”场景中。但是,坦率地说,我建议使用 [Flags] enum 相反,即

    [Flags]
    enum FoodOptions {
        None = 0,
        Fruits = 1,
        Drinks = 2,
        Lunch = 4,
        Dinner = 8,
    }
    
    var options = FoodOptions.None;
    if(model.Fruits.Value) options |= FoodOptions.Fruits;
    if(model.Drinks.Value) options |= FoodOptions.Drinks;
    if(model.Lunch.Value) options |= FoodOptions.Lunch;
    if(model.Dinner.Value) options |= FoodOptions.Dinner;
    

    它只是整数。

        2
  •  0
  •   Md. Tazbir Ur Rahman Bhuiyan    6 年前

    稍微升级一下代码。我想这可能对你有帮助。

    using System;
    using System.Text;
    
    public class Program
    {
    public static void Main()
    {
           StringBuilder options = new StringBuilder();
        Food model= new Food();
    
    
        if (model.Fruits.HasValue)
        {
            options.Append("FR,");
        }
        if (model.Drinks.HasValue)
        {
            options.Append("DR,");
        }
        if (model.Lunch.HasValue)
        {
    
            options.Append("LU,");
        }
        if (model.Dinner.HasValue)
        {
            options.Append("DI,");
        }
        Console.WriteLine(options);
    }
    }
    
    public class Food{
    public int? Fruits{get;set;}
    public int? Drinks{get;set;}
    public int? Lunch{get;set;}
    public int? Dinner{get;set;}
    
    public Food(){
        Fruits=1;
        Drinks=null;
        Lunch=2;
        Dinner=3;
    }
    
    }