当变量等于零时隐藏标签

时间:2012-01-16 03:28:42

标签: c# conditional-operator

我想隐藏一个StopWatch标签,当它等于0时,我怎么能用条件运算符来做?

using System;
using System.Diagnostics;
using System.Threading;

namespace FileTransfer_Socket_Client
{
class transferRate
{
    static Stopwatch stopWatch = new Stopwatch();
    public static void timeLeft()
    {
        Thread StimeLeft = new Thread(Start);
        StimeLeft.Start();
    }

    private static void Start()
    {
        int rate = 0;
        int left = 0;
        int prevSum = 0;
        stopWatch.Start();
        while (fileTransfer.client.Connected)
        {
            if (fileTransfer.sum != 0)
            {
                rate = (fileTransfer.sum-prevSum)/1024;
                left = ((fileTransfer.fileSize - fileTransfer.sum)/ 1024) / rate;
                TimeSpan t = TimeSpan.FromSeconds(left);
                Program.mainForm.AppendLabel(string.Format("{0}kb/s  timeleft: {1:D2}:{2:D2}:{3:D2}", rate, t.Hours, t.Minutes, t.Seconds));
                prevSum = fileTransfer.sum;
                Thread.Sleep(1000);
            }
        }
        stopWatch.Stop();
        stopWatch.Reset();
    }
}}

1 个答案:

答案 0 :(得分:5)

虽然有更多“有趣”的方法可以完成,if/else是最基本的方式:

if (t.TotalMinutes < 1) {
   Program.mainForm.AppendLabel(string.Format("{0}kb/s  timeleft: {1:D2}", rate, t.Seconds));
} else {
   Program.mainForm.AppendLabel(string.Format("{0}kb/s  timeleft: {1:D2}:{2:D2}:{3:D2}", rate, t.Hours, t.Minutes, t.Seconds))
}

请注意,我们可以这样写,并避免重复方法调用:

String text;
if (t.TotalMinutes < 1) {
   text = string.Format("{0}kb/s  timeleft: {1:D2}", rate, t.Seconds);
} else {
   text = string.Format("{0}kb/s  timeleft: {1:D2}:{2:D2}:{3:D2}", rate, t.Hours, t.Minutes, t.Seconds);
}
Program.mainForm.AppendLabel(text);

或者我们可以使用三元(条件运算符):

var text = t.TotalMinutes < 1
    ? string.Format("{0}kb/s  timeleft: {1:D2}", rate, t.Seconds)
    : string.Format("{0}kb/s  timeleft: {1:D2}:{2:D2}:{3:D2}", rate, t.Hours, t.Minutes, t.Seconds);
Program.mainForm.AppendLabel(text);

或者我们可以把它完全放在一个方法中:

string FormatRemainingText (int rate, TimeSpan t) {
    if (t.TotalMinutes < 1) {
        return string.Format("{0}kb/s  timeleft: {1:D2}", rate, t.Seconds);
    } else {
        return string.Format("{0}kb/s  timeleft: {1:D2}:{2:D2}:{3:D2}", rate, t.Hours, t.Minutes, t.Seconds);
    }
}
Program.mainForm.AppendLabel(FormatRemainingText(rate, t));

快乐的编码。