Accessing class member from static method

后端 未结 3 855
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 07:30

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 fro

3条回答
  •  悲哀的现实
    2020-12-11 08:12

    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.

提交回复
热议问题