2016-07-26 25 views
2

コースの一部としてストップウォッチとして機能する小さなプログラムを作成しています。 私が抱えている問題は、私がコンパイルしようとすると私のProgram.csクラスの私のDuration()メソッドにCannot convert from void to boolを得ているということです。 メソッドが返されますTimeSpanC#ボイドからブールに変換できません - CS1503

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; 
     } 
    } 
} 
+4

期間を)voidメソッドですが、あなたはそれをWriteLineメソッドしよう。それはうまくいきません。 –

+2

"Public TimeSpan Duration()"を意味しますか? –

+2

あなたはコードブラインドに行かなければなりません:P – BugFinder

答えて

8

DurationConsole.WriteLineで使用するTimeSpan返す必要があります:(

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

    ... 

    Console.WriteLine(stopwatch.Duration()); 
+0

これは一度も使われていないので、 '_duration'を維持して設定する必要はありません。 – Shautieh

+0

私はばかな気分です。私はそれを逃したとは信じられません。明らかに、それは無効を返すだろう!ありがとう。 –

+2

注意として、元の例外にvoidからboolへの変換が言及されている場合は、Console.WriteLineの最初の(アルファベット順の)メソッドシグネチャを検索する( 'void'パラメータ用のシグネチャがないため) 「ブール」。 – Kilazur

関連する問題