问题描述
我知道,如果你使用一个静态变量,它的值是所有用户共享。
i know that if you use a static variable that it's value is shared across all users.
static string testValue = "";
protected void SomeMethod(object sender, EventArgs e)
{
testValue = TextBox1.Text;
string value = TestClass.returnString(TextBox1.Text); // <-- return from a static method
}
所以在这种情况下,如果1个用户进入到网站,并把一个值转换成文本框,字符串 testValue
将由另一个值,如果另一用户输入的东西覆盖在文本框中。 (我想?)
so in this case, if 1 user goes to a website and puts a value into the textbox, the string testValue
will be overwritten by another value if another user enters something in the textbox. (i think?)
我现在有这个类:
public class TestClass
{
public static string returnString(string msg)
{
return msg;
}
}
我现在的问题是,如果我用一个静态方法,是藏汉所有用户共享该方法的返回值?或者是总是一个独特的每用户价值?
my question now is, if i use a static method, is the return value of that method shared for all users aswell? or is that always a "unique" value per user ?
让说,这种方法被称为5次,5个不同的用户,将在静态方法返回一个特定的用户输入的值,或者是有可能,1用户获得另一个用户输入一个值?
lets say that this method is called 5 times, by 5 different users, will this static method return the value a particular user has entered, or is it possible that 1 user gets a value that another user entered ?
推荐答案
您的问题是:
我现在的问题是,如果我用一个静态方法,是的返回值
为藏汉所有用户共享的方法?或者是总是一个独一无二
每个用户的价值?
和答案是,这取决于。用你的例子:
And the answer is, it depends. Using your example:
public class TestClass
{
public static string returnString(string msg)
{
return msg;
}
}
在这种情况下,5个不同的用户将(最有可能的)在5种不同的字符串传递给静态方法。因此,他们会得到倒退5型动物字符串。因此,对于这种情况:
In this case, 5 different users would (most likely) pass in 5 different strings to the static method. Therefore they would get back five differents strings. So for this case:
string value = TestClass.returnString(TextBox1.Text);
每个用户还是会回到什么他们输入到自己的文本框。如果,在另一方面,code是这样的:
each user would get back whatever they had typed into their own TextBox. If, on the other hand the code was this:
string value = TestClass.returnString(testValue);
他们将所有的东西拿回来正好是在返回时的静态字符串。
They would all get back what happened to be in the static string at the time of the return.
所以要牢记的规则是:
- 如果该方法使用静态成员变量,有互相影响的结果不同的用户的风险。这其中的方法是静态的还是不正确的regradless。
- 如果该方法仅使用呼叫参数和局部变量,并且呼叫参数本身没有指向statisc成员变量,来自不同的用户的呼叫将不会互相影响。
这篇关于静态变量和静态方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!