重构代码并开发干净的代码

use*_*915 0 .net c# asp.net c#-4.0

我有一个dto如下:

public class DaysDetails
{
 public bool Sun {get;set;}
 public bool Mon {get;set;}
 ...
 public bool Sat {get;set;} //All 7 days of the week
}
Run Code Online (Sandbox Code Playgroud)

我有一个方法,它检查是否检查了日期并构建逗号分隔的字符串格式.例如:如果检查星期日和星期一,则输出为"0,1"(对应于天数的数字)

pubic string ConstructDays(DaysDetails d)
{
 StringBuilder constructDays = new StringBuilder();
 if(d.Sun == true)
  { 
    constructDays.Append("0");
  }
 if(d.Mon == true)
 {
   constructDays.Append("1");
  }
 ..... //So on for all seven days
 string day = Convert.toString(constructDays);

 if(day != string.Empty && day[0] == ",")
   day = day.Remove(0,1);
 return day;
}
Run Code Online (Sandbox Code Playgroud)

我需要将此函数转换为更易于维护的代码和简化版本.这有什么可以改进的?

JSt*_*ard 5

您可以通过将每个bool转换为int并加入生成的集合来简化代码.

public class DaysDetails
{
    public bool Sun { get; set; }
    public bool Mon { get; set; }
    public bool Sat { get; set; }
}

public string ConstructDays(DaysDetails d)
{
    var week = new[]
    {
        Convert.ToInt32(d.Sat),
        Convert.ToInt32(d.Sun),
        Convert.ToInt32(d.Mon),
    };
    return string.Join(",",  week);
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您寻找的不仅仅是0/1:

public string ConstructDays(DaysDetails d)
{
    var week = new[]
    {
        d.Sat ? 0 : -1,
        d.Sun ? 1 : -1,
        d.Mon ? 2 : -1,
        //...//
    }.Where(x => x != -1);
    return string.Join(",",  week);
}
Run Code Online (Sandbox Code Playgroud)