gpt4 book ai didi

c# - 从静态方法获取访问权限

转载 作者:太空狗 更新时间:2023-10-29 20:46:23 26 4
gpt4 key购买 nike

今天早上我的大脑不工作了。我需要一些帮助来从静态方法访问一些成员。这是一个示例代码,我如何修改它以便 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
}
}

最佳答案

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 的东西,那么使用前者。

关于c# - 从静态方法获取访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2049884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com