2009-12-28 156 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屬性,因爲它在所有頁面生命週期中都可用。