将多个if语句变为短语句

时间:2019-02-12 10:18:26

标签: c# .net if-statement

我正在尝试根据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 个答案:

答案 0 :(得分:5)

类似的方法可能有一些优点:

    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)),因此它将避免大量中间字符串({{ 1}})。但是,坦率地说,我建议改用+=,即

[Flags] enum

这只是整数。

答案 1 :(得分:0)

对您的代码进行一些升级。认为这可能会对您有所帮助。

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

}