2009-12-28 166 views
0

我试图在一个pagerequest期间用livetime设置一个全局变量。在c#中设置全局变量class

在经典ALS我用这个像这样:


dim VariableName 
VariableName = "test"; 

sub testsub() 
    VariableName += VariableName + "new" 
    response.write VariableName 
end sub 

response.write VariableName '-> test 
testsub() '-> testnew 

现在在asp.net我tryed设置变量在我的课是这样的:

public static class MyClass 
{ 
    public static string GlobalVar = "test"; 

    public static string MyMethod() 
    { 
     GlobalVar += GlobalVar + "new"; 

     return GlobalVar; 
    } 
} 

但是现在,问题是,这个变量就像一个应用变量,其生命周期超过了所有的pagerequest。

在哪里可以定义一个生命期间的变量,在一个请求期间可用于所有方法和其他类?

+0

这有坏设计写在它上面 – 2009-12-28 12:53:34

回答

5
HttpContext.Current.Items["ThisVariableHasRequestScope"] = "SomethingFancy"; 

编辑:

一个简单的例子

AClass.cs:

public class AClass { 
    public void Something() { 
     // Set the value 
     HttpContext.Current.Items["Test"] = "xxx"; 
    } 
} 

BClass.cs

public class BClass{ 
    public void SomethingElse() { 
     // Get the value 
     var test = HttpContext.Current.Items["Test"] as string; 
    } 
} 
+0

谢谢你的回答。我想在MyClass中设置这个变量,而不是在MyMethod()中。因为我必须在其他文件和类中使用这个全局变量。我如何设置这个变量? – roniX 2009-12-28 16:35:58

+0

不客气。我已经添加了一个小例子。 – Diadistis 2009-12-28 16:53:37

2

尝试使用ASP.NET 会话并查看它是否符合您的需求。

0

你也可以使用Page.Context属性,因为它在所有页面生命周期中都可用。