C# 变量赋值问题
当我返回字符串 timeTaken 时,它是 null,并且它在 IDE 上这么说,尽管它已在 main 方法中定义 (TimeSpan timeTaken = timeTaken = timeTaken;)
class Program
{
public static string timeTaken;
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
Stopwatch timer = new Stopwatch();
timer.Start();
using (var response = request.GetResponse());
timer.Stop();
TimeSpan timeTaken = timer.Elapsed;
...
}
}
如何输出 timeTaken?
When I return the string timeTaken, it is null, and it says this on the IDE to, although it has been defined in the main method (TimeSpan timeTaken = timer.Elapsed;)
class Program
{
public static string timeTaken;
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
Stopwatch timer = new Stopwatch();
timer.Start();
using (var response = request.GetResponse());
timer.Stop();
TimeSpan timeTaken = timer.Elapsed;
...
}
}
How can I output timeTaken?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您定义一个具有相同名称的局部变量
,该变量隐藏您的静态类字段。
要输出timer.Elapsed的值,你可以这样写:
You define a local variable with the same name
which hides your static class field.
To output the value of timer.Elapsed you could write something like this:
有两个 timeTaken 变量,一个是 Main 函数的本地变量,另一个是类的静态成员。要显式引用该字符串,请使用
Program.timeTaken
。无论如何,如果您将代码重构为具有不同的名称,那就更好了。There is two timeTaken variable, one local to rthe Main function, the other one is a static member of the class. To explicitly refer to the string one use
Program.timeTaken
. Anyway is better if you refactor the code to have different names.您可能想要更像这样的东西:-
You probably want something more like this:-
您犯了一个简单的错误:您在
static void Main(...)
行中再次定义了变量“timeTaken”,这将隐藏静态定义。要回到静态类字段,请
考虑命名(例如将静态字段命名为
_timeTaken
或者只是使用
而不是
You made a simple mistake: you define the variable "timeTaken" once again inside
static void Main(...)
on the lineThis will shadow the static definition. To get back to the static class field use
think about naming (for example name your static field
_timeTaken
or just use
instead of