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

标签 c# .net

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

我看不到它在哪里设置为 void。也许是 C# 运行时中较低级别的东西?不确定。

程序.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;
        }
    }
}

最佳答案

Duration 应返回 TimeSpan 以在 Console.WriteLine 中使用:

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

    ...

    Console.WriteLine(stopwatch.Duration()); 

关于C# 无法从 void 转换为 bool - CS1503,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38592496/

相关文章:

.net - 带有过滤条件的 LINQ 连接

c# - 遍历 StartDate 和 EndDate 之间的每一天

c# - WindowsIdentity 缺失组 - 特别是管理员组

c# - 如何延迟发送电子邮件?

c# - 临时存储一个 Delegate 以供以后调用

c# - .NET TextBox 更新时挂起

.net - 从 List<> 中获取单个随机元素的最佳方法是什么?

.net - 如何使用默认为 DateTimeKind.Utc 的 DateTime 值进行 DataSet.Fill?

c# - 为什么我不能在初始化程序中初始化只读变量?

javascript - 使用 jquery 从 displayfor 获取值