-2

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

1 回答 1

12

我猜你想要做的是这样的

if (span.TotalSeconds >= 60 * 60)
{
    Console.WriteLine("hours");
}
else if (span.TotalSeconds >= 60)
{
    Console.WriteLine("minutes");
}
else
{
    Console.WriteLine("seconds");
}
于 2012-07-12T16:58:39.107 回答