using System;
using System.Diagnostics;
using System.Threading;
class MainClass {
public static void Main (string[] args) {
Console.WriteLine(watch);
}
public static int Number (int num) {
watch = new Stopwatch();
watch.Start();
Console.ReadLine();
watch.Stop();
return watch;
}
}我有一个问题,就是手表在目前的情况下不存在。这可能是一个很容易解决的问题,但我对c#还不熟悉,所以请认真考虑这个问题。谢谢!
发布于 2021-03-23 19:06:14
更改代码,如下所示
using System;
using System.Diagnostics;
using System.Threading;
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine(GetElapsedTime());
}
public static long GetElapsedTime()
{
// You have to specify your variable like below
// for more information : https://www.w3schools.com/cs/cs_variables.asp
Stopwatch watch = new Stopwatch();
watch.Start();
Console.ReadLine();
watch.Stop();
return watch.ElapsedMilliseconds;
}
}我将您的方法"Number“更改为"GetElapsedTime”,因为它不是一个合适的名称。
我想您的目的是返回经过的时间,我修正了代码。欲了解更多信息,请使用下面的链接:
https://www.w3schools.com/cs/cs_variables.asp
https://www.w3schools.com/cs/cs_methods.asp https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=net-5.0
发布于 2021-03-23 19:03:04
以便在多个方法中使用变量。您需要在global scope中声明它。
示例:
class MainClass{
public static Stopwatch watch;
public static void Main(string[] args){
watch = new Stopwatch();
Watch_Start();
Watch_Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
public static void Watch_Start(){
watch.Start();
}
public static void Watch_Stop(){
watch.Stop();
}
}https://stackoverflow.com/questions/66769462
复制相似问题