从静态方法获取访问权限

Mik*_*den 6 c# static-methods

我的大脑今天早上没有工作.我需要一些帮助从静态方法访问一些成员.下面是一个示例代码,如何修改它以便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
    }  
}
Run Code Online (Sandbox Code Playgroud)

jas*_*son 10

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

protected static int testInt { get; set; }
Run Code Online (Sandbox Code Playgroud)

没问题

public static void TestMethod(TestPage testPage) {
    Console.WriteLine(testPage.testInt);
}
Run Code Online (Sandbox Code Playgroud)

其中哪一个是正确的,在很大程度上取决于你想要建模的东西.如果testInt表示实例的状态TestPage则使用后者.如果testInt是类型的东西,TestPage那么使用前者.


Luk*_*keH 6

两个选项,取决于您正在尝试做什么:

  • 让你的testInt财产保持静止.
  • 改变TestMethod以便它将一个实例TestPage作为参数.