目前,我收到錯誤「非靜態字段方法或屬性需要對象引用」。我的代碼如下:如何創建HttpContext的實例?
using MyApp.Global;
namespace MyApp.MyNamespace
{
public class MyClass:System.Web.UI.Page
{
//Toolbox is inside Global, GetCurrentCookieData is a static method
private CookieData cd = Toolbox.GetCurrentCookieData(HttpContext.Current);
//the above was changed and resolved the first error, but another error
//just popped up. Below, I get the error: cd denotes field
//where class was expected
private int CompanyID = Util.GetCompanyIDByUser(cd.Users);
protected override void OnLoad(EventArgs e)
{
//snip
}
protected void MyEventHandler(object sender, EventArgs e)
{
//snip
}
}
}
目前,我的每一個方法需要使用CD,所以不是創建每個方法中的變量,我一直在尋找一種方式來聲明它的類,可將其到所有方法。當我嘗試在方法中設置cd時,它工作正常。我搜索了一下,似乎我必須有一個頁面的實例才能在那裏使用,但這不起作用。所以我真的誤解了這是如何工作的。任何人都可以將我指向正確的方向嗎?
編輯:我添加了靜態關鍵字到CD,爲了解決'cd表示期望類'的錯誤。這是很好的實現嗎?
編輯:我打算在下面標記正確答案並提出一個新問題,因爲我認爲這是值得的。
它看起來像做了工作,但我必須澄清我的問題,因爲它看起來稍微有點多。 – 2009-06-09 18:42:15