[英]variable in static methods inside static class
please consider this code : 请考虑以下代码:
1)public static class MyClass
2){
3) public static DateTime MyMethod(DateTime dt)
4) {
5) DateTime temp = new DateTime();
6) temp = dt.AddDays(1);
7) return temp;
8) }
9)}
Does temp
variable has instance per any calls to MyMethod
? 每次调用
MyMethod
temp
变量都有实例吗? or because it is in a static method inside static class just one instance of temp
variable allocate in memory? 或者因为它在静态类中的静态方法中只有一个
temp
变量实例在内存中分配?
thanks 谢谢
temp
is neither a static nor an instance variable, it is a local variable. temp
既不是静态变量也不是实例变量,它是局部变量。 It absolutely does not matter whether the method in which it is declared is static or not: the variable's scope starts at the point of its declaration, and ends at the closing curly brace }
of the scope in which it is declared. 声明它的方法是否为静态绝对无关紧要:变量的范围从其声明点开始,并在声明它的范围的结束大括号
}
结束。 Each executing thread that goes through MyMethod
gets its own copy of temp
, which is invisible anywhere outside the variable's scope. 通过
MyMethod
每个执行线程都获得自己的temp
副本,该变量在变量范围之外的任何地方都是不可见的。
Does temp variable has instance per any calls to MyMethod?
每次调用MyMethod时,temp变量都有实例吗?
If you mean "does each call to MyMethod
get a separate temp
variable?" 如果你的意思是“每次调用
MyMethod
都会获得一个单独的temp
变量吗?” then the answer is yes. 那么答案是肯定的。
The fact that it's a static method in a static class is irrelevant - it's a local variable, so you get a "new" local variable on each call. 它是静态类中的静态方法这一事实无关紧要 - 它是一个局部变量,因此每次调用时都会得到一个“新的”局部变量。
temp
has one instance per call. temp
每个调用有一个实例。
BTW I'm missing possibility to define static local variables in static methods as in C++. 顺便说一下,我缺少在静态方法中定义静态局部变量的可能性,就像在C ++中一样。
临时变量,即使在静态方法中,也必须声明为静态,否则它只是在该实例中本地创建,然后在方法调用结束时被吹走。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.