目前,我收到错误"非静态字段方法或属性需要对象引用".我的代码如下:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
目前,我的每个方法都需要使用cd,因此我不是在每个方法中创建一个变量,而是在类中声明它并让它可用于所有方法.当我尝试在方法中设置cd时,它工作正常.我已经google了,似乎我必须有一个Page的实例才能在那里使用,但这不起作用.所以我真的误解了它是如何工作的.谁能指出我正确的方向?
编辑:我添加了静态关键字到cd,以解决'cd表示期望类的字段'错误.这是好的实施吗?
编辑:我将在下面标记正确的答案并提出一个新问题,因为我认为这是值得的.
| 归档时间: |
|
| 查看次数: |
6369 次 |
| 最近记录: |