Why can't I use the .Restart () stopwatch?

I try to call Restart()a stopwatch on an instance, but when I try to call it, the following error appears:

Assets / scripts / controls /SuperTouch.cs(22.59): error CS1061: Type System.Diagnostics.Stopwatch' does not contain a definition for Restart 'and do not use the Restart' of type System.Diagnostics.Stopwatch' extension method (can you not use the directive or assembly reference?)

This is my code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;

namespace Controls
{

    public class SuperTouch
    {
            public Vector2 position { get { return points [points.Count - 1]; } }
            public float duration { get { return (float)stopwatch.ElapsedMilliseconds; } }
            public float distance;
            public List<Vector2> points = new List<Vector2> ();

            public Stopwatch stopwatch = new Stopwatch ();

            public void Reset ()
            {
                    points.Clear ();
                    distance = 0;
                    stopwatch.Restart ();
            }
    }
}
+5
source share
4 answers

I assume that you are using .Net Framework 3.5or below where the method Restart Stopwatchdoes not exist.

If you want to reproduce the same behavior, you can do it as follows.

Stopwatch watch = new Stopwatch();
watch.Start();
// do some things here
// output the elapse if needed
watch = Stopwatch.StartNew(); // creates a new Stopwatch instance 
                              // and starts it upon creation

StartNew .Net Framework 2.0

StartNew : .

, , .

.

public static class ExtensionMethods
{
    public static void Restart(this Stopwatch watch)
    {
        watch.Stop();
        watch.Start();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Stopwatch watch = new Stopwatch();
        watch.Restart(); // an extension method
    }
}
+6

, pre 4.0, , Reset Start Restart.

+9

Unity Engine .NET 2.0. , .NET 4.0 Restart. .NET, . , Start Reset.

0

( ) .

  public static class StopwatchExtensions
  {
    /// <summary>
    /// Support for .NET Framework <= 3.5
    /// </summary>
    /// <param name="sw"></param>
    public static void Restart(this Stopwatch sw)
    {
      sw.Stop();
      sw.Reset();
      sw.Start();
    }
  }
0

All Articles