开发者

Gaining access from a static method

开发者 https://www.devze.com 2022-12-16 07:23 出处:网络
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

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 TestMe开发者_如何转开发thod()
    {
       // I am accessing this method from a PageMethod call on the clientside
       // No access here
    }  
}


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.


Two options, depending on what exactly you're trying to do:

  • Make your testInt property static.
  • Alter TestMethod so that it takes an instance of TestPage as an argument.


protected static int testInt { get; set; }

But be careful with threading issues.


Remember that static means that a member or method belongs to the class, instead of an instance of the class. So if you are inside a static method, and you want to access a non-static member, then you must have an instance of the class on which to access those members (unless the members don't need to belong to any one particular instance of the class, in which case you can just make them static).

0

精彩评论

暂无评论...
验证码 换一张
取 消