尝试在方法外部使用StopWatch

时间:2014-11-10 19:41:55

标签: c# stopwatch

我正在尝试创建一个秒表表单。我希望能够按下一个按钮来获得一圈时间就像一个普通的秒表。由于我不明白的原因,我不能定义一个Stopwatch变量,并在另一个方法中调用它的构造函数。我如何制作StopWatch变量以便我可以在其他方法中使用它?如果我不应该使用StopWatch我应该做什么?

namespace _Hard0002_StopWatch {
    public partial class StopWatch : Form {
        StateEnum state;
        StopWatch stopWatch;

        public StopWatch() {
            InitializeComponent();
            state = StateEnum.Stoped;
        }

        private void StartButton_Click(object sender, EventArgs e) {
            if (state == StateEnum.Stoped) {
                stopWatch = Stopwatch.StartNew();
                state = StateEnum.Started;
                ChangeFormTittle("Started");
                TimeKeeperText.Text = "0.0";
            }
        }

    private void LapButton_Click(object sender, EventArgs e) {
        //save time elapsed to a string array
        stopWatch.getElapsedTime()//I know this isn't how you call it I just worded it to be readable.
    }

当我尝试在stopWatch

中声明StartButton_Click()时,这是我遇到的错误

Cannot implicitly convert type 'System.Diagnostics.Stopwatch' to '_Hard0002_StopWatch.StopWatch'

1 个答案:

答案 0 :(得分:5)

C#的秒表是Stopwatch。你的班级是StopWatch。你声明你的变量:

StopWatch stopWatch;

然后初始化它:

stopWatch = Stopwatch.StartNew();

使用两个不同的对象。最好将表单重命名为StopwatchForm,以防止让自己更加困惑。