6

今天早上我的大脑不工作了。我需要一些帮助来从静态方法访问一些成员。这是一个示例代码,我该如何修改它以便TestMethod()可以访问testInt

public class TestPage
{ 
    protected int testInt { get; set; }

    protected void BuildSomething
    {
      // Can access here
    }

    [ScriptMethod, WebMethod]
    public static void TestMethod()
    {
       // I am accessing this method from a PageMethod call on the clientside
       // No access here
    }  
}
4

4 回答 4

10

testInt被声明为实例字段。如果没有对定义类的实例的引用,方法就不可能static访问实例字段。因此,要么声明testInt为静态,要么更改TestMethod为接受TestPage. 所以

protected static int testInt { get; set; }

没关系

public static void TestMethod(TestPage testPage) {
    Console.WriteLine(testPage.testInt);
}

其中哪一个是正确的在很大程度上取决于您要建模的内容。如果testInt表示实例的状态,TestPage则使用后者。如果testInt与类型有关,TestPage则使用前者。

于 2010-01-12T15:10:02.017 回答
6

两种选择,具体取决于您要执行的操作:

  • 使您的testInt财产静态。
  • 改变TestMethod,以便它接受一个实例TestPage作为参数。
于 2010-01-12T15:08:41.223 回答
4
protected static int testInt { get; set; }

但要小心线程问题。

于 2010-01-12T15:07:41.973 回答
4

请记住,这static意味着成员或方法属于类,而不是类的实例。因此,如果你在一个静态方法中,并且你想访问一个非静态成员,那么你必须有一个类的实例来访问这些成员(除非这些成员不需要属于任何一个特定的实例类的,在这种情况下,您可以将它们设为静态)。

于 2010-01-12T15:09:58.030 回答