从静态方法访问类成员

Jer*_*emy 4 c# asp.net static non-static

我知道有很多线程在讨论这个问题,但到目前为止我还没有找到一个直接帮助我的情况.我需要从静态和非静态方法访问类的成员.但如果成员是非静态的,我似乎无法从静态方法中获取它们.

public class SomeCoolClass
{
    public string Summary = "I'm telling you";

    public void DoSomeMethod()
    {
        string myInterval = Summary + " this is what happened!";
    }

    public static void DoSomeOtherMethod()
    {
        string myInterval = Summary + " it didn't happen!";
    }
}

public class MyMainClass
{
    SomeCoolClass myCool = new SomeCoolClass();
    myCool.DoSomeMethod();

    SomeCoolClass.DoSomeOtherMethod();
}
Run Code Online (Sandbox Code Playgroud)

您如何建议我从任何一种方法获得摘要?

Jon*_*eet 9

您如何建议我从任何一种方法获得摘要?

你需要传递myCoolDoSomeOtherMethod- 在这种情况下你应该使它成为一个实例方法开始.

从根本上说,如果它需要该类型实例的状态,为什么要将它设为静态?


Man*_*ntz 7

您无法从静态方法访问实例成员.静态方法的重点在于它们与类实例无关.