Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gaining access from a static method

My brain is not working this morning. I need some help accessing some members from a static method. Here is a sample code, how can I modify this so that TestMethod() has access to 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
    }  
}
like image 272
Mike Fielden Avatar asked Jan 12 '10 15:01

Mike Fielden


1 Answers

testInt is declared as an instance field. It is impossible for a static method to access an instance field without having a reference to an instance of the defining class. Thus, either declare testInt as static, or change TestMethod to accept an instance of TestPage. So

protected static int testInt { get; set; }

is okay as is

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

Which of these is right depends very much on what you're trying to model. If testInt represents state of an instance of TestPage then use the latter. If testInt is something about the type TestPage then use the former.

like image 66
jason Avatar answered Sep 28 '22 03:09

jason