C#无法从void转换为bool - CS1503

时间:2016-07-26 14:22:45

标签: c# .net

我正在编写一个小程序作为课程的一部分作为秒表。 我遇到的问题是,当我尝试编译时,我在Cannot convert from void to bool课程中的Duration()方法上获得了Program.cs。 该方法应返回TimeSpan

我无法看到它被设置为void的位置。可能是C#运行时中较低级别的东西?不确定。

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stopwatch
{
    class Program
    {
        static void Main(string[] args)
        {
            var stopwatch = new StopWatchController();
            stopwatch.Start();
            stopwatch.Start(); // Second Start() method should throw an exception
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Duration()); // Error appears here
        }
    }
}

StopwatchController.cs

using System;
using System.Runtime.CompilerServices;

namespace Stopwatch
{
    public class StopWatchController
    {
        private DateTime _startTime;
        private DateTime _finishTime;
        private TimeSpan _duration;
        private bool _isWatchRunning;

        public void Start()
        {
            if (!_isWatchRunning)
            {
                _isWatchRunning = !_isWatchRunning;
                _startTime = DateTime.Now;
            }
            else
            {
                throw new Exception("InvalidArgumentException");
            }
        }

        public void Stop()
        {
            _isWatchRunning = false;
            _finishTime = DateTime.Now;
        }

        public void Duration() // I'm an idiot
        {
            _duration = _finishTime - _startTime;
        }
    }
}

1 个答案:

答案 0 :(得分:8)

Duration应返回TimeSpan使用Console.WriteLine

    public TimeSpan Duration()
    {
        return _duration = _finishTime - _startTime;
    }

    ...

    Console.WriteLine(stopwatch.Duration());