Accessing class member from static method

筅森魡賤 提交于 2019-11-27 07:13:02

问题


I know there are a lot of threads talking about this but so far I haven't found one that helps my situation directly. I have members of the class that I need to access from both static and non-static methods. But if the members are non-static, I can't seem to get to them from the static methods.

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

How would you suggest I get Summary from either type of method?


回答1:


How would you suggest I get Summary from either type of method?

You'll need to pass myCool to DoSomeOtherMethod - in which case you should make it an instance method to start with.

Fundamentally, if it needs the state of an instance of the type, why would you make it static?




回答2:


You can't access instance members from a static method. The whole point of static methods is that they're not related to a class instance.




回答3:


You simply can't do it that way. Static methods cannot access non static fields.

You can either make Summary static

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!";
    }
}

Or you can pass an instance of SomeCoolClass to DoSomeOtherMethod and call Summary from the instance you just passed :

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!";
    }
}

Anyway I can't really see the goal you're trying to reach.



来源:https://stackoverflow.com/questions/11906737/accessing-class-member-from-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!