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

3th*_*1ll 2 .net c#

我正在写一个小程序作为课程的一部分作为秒表.我遇到的问题是,当我尝试编译时 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 8

Duration应该返回TimeSpan用于Console.WriteLine:

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

    ...

    Console.WriteLine(stopwatch.Duration()); 
Run Code Online (Sandbox Code Playgroud)

  • 作为一个注释,如果原始异常提到从void转换为bool,那是因为它搜索Console.WriteLine的第一个(按字母顺序)方法签名(因为它没有一个用于`void`参数),这需要一个`bool`. (2认同)