Switch + TimeSpan

时间:2012-07-12 16:52:38

标签: c#

我如何将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;
    }

1 个答案:

答案 0 :(得分:12)

我想你要做的就是这样的事情

if (span.TotalSeconds >= 60 * 60)
{
    Console.WriteLine("hours");
}
else if (span.TotalSeconds >= 60)
{
    Console.WriteLine("minutes");
}
else
{
    Console.WriteLine("seconds");
}