为什么我无法使用秒表.重新启动()

本文关键字:重新启动 为什么 | 更新日期: 2023-09-27 18:37:21

我正在尝试在秒表实例上调用Restart(),但在尝试调用它时收到以下错误:

资产/脚本/控件/超级触控.cs(22,59):错误 CS1061:类型 System.Diagnostics.Stopwatch' does not contain a definition for 重新启动"并且找不到Restart' of type 系统诊断.秒表的扩展方法(您是否缺少使用 指令还是程序集引用?

这是我的代码:

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 ();
            }
    }
}

为什么我无法使用秒表.重新启动()

我猜你使用的是4.0之前的框架,这意味着你必须使用ResetStart而不是Restart

我猜您使用的是不存在Stopwatch Restart方法的.Net Framework 3.5或更低。

如果要复制相同的行为,可以这样做。

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

有关开始新方法的更多详细信息: 秒表。启动新方法

或者,您可以为自己创建一个扩展方法。

这是一个模型和用法。

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
    }
}

不要调用多个方法(容易出现人为错误),而是使用扩展方法。

  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();
    }
  }

Unity 引擎使用 .NET 2.0 的子集。正如其他人所说,Restart是在 .NET 4.0 中添加的。此有用的页面显示可以安全使用的所有 .NET 函数。如您所见,StartReset都存在。