ron*_*niX 0 c# asp.net global-variables
我试图在一个页面请求期间设置一个带有实时的全局变量.
在经典als中我使用这样:
dim VariableName
VariableName = "test";
sub testsub()
VariableName += VariableName + "new"
response.write VariableName
end sub
response.write VariableName '-> test
testsub() '-> testnew
Run Code Online (Sandbox Code Playgroud)
现在在asp.net中我尝试在我的类中设置变量,如下所示:
public static class MyClass
{
public static string GlobalVar = "test";
public static string MyMethod()
{
GlobalVar += GlobalVar + "new";
return GlobalVar;
}
}
Run Code Online (Sandbox Code Playgroud)
但现在,问题是,这个变量就像一个应用程序变量,具有超过所有pagerequest的生命周期.
在一个请求期间,我可以在哪里定义具有生命周期的变量,并且在所有方法和其他类中都可以使用?
HttpContext.Current.Items["ThisVariableHasRequestScope"] = "SomethingFancy";
Run Code Online (Sandbox Code Playgroud)
编辑:
一个简单的例子
AClass.cs:
public class AClass {
public void Something() {
// Set the value
HttpContext.Current.Items["Test"] = "xxx";
}
}
Run Code Online (Sandbox Code Playgroud)
BClass.cs
public class BClass{
public void SomethingElse() {
// Get the value
var test = HttpContext.Current.Items["Test"] as string;
}
}
Run Code Online (Sandbox Code Playgroud)