从静态方法访问类成员

时间:2012-08-10 17:46:00

标签: 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();
}

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

3 个答案:

答案 0 :(得分:8)

  

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

您需要将myCool传递给DoSomeOtherMethod - 在这种情况下,您应该将其作为一个实例方法开始。

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

答案 1 :(得分:7)

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

答案 2 :(得分:1)

你根本无法做到这一点。静态方法无法访问非静态字段。

您可以Summary静态

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

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

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

或者您可以将SomeCoolClass的实例传递给DoSomeOtherMethod,并从刚刚传递的实例中调用Summary

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

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

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

无论如何,我无法真正看到你想要达到的目标。

相关问题