我如何将Switch
声明与TimeSpan
一起使用?
switch (myTimeSpan)
{
case TimeSpan.Minutes:
Console.WriteLine("Case 1");
break;
case TimeSpan.Hours:
Console.WriteLine("Case 2");
break;
case TimeSpan.Seconds:
Console.WriteLine("Case 2");
break;
}
编辑 - 添加了答案
C#7可以处理带有模式匹配的Switch
语句
switch(DateTime.Now-lastDate) {
case var t when t.Days>720:
changefreq="never";
break;
case var t when t.Days>365:
changefreq="yearly";
break;
case var t when t.Days>180:
changefreq="monthly";
break;
case var t when t.Days>30:
changefreq="weekly";
break;
default:
changefreq="daily";
break;
}
答案 0 :(得分:12)
我想你要做的就是这样的事情
if (span.TotalSeconds >= 60 * 60)
{
Console.WriteLine("hours");
}
else if (span.TotalSeconds >= 60)
{
Console.WriteLine("minutes");
}
else
{
Console.WriteLine("seconds");
}