Why can't I call a public method in another class?

后端 未结 4 664
臣服心动
臣服心动 2021-02-05 22:27

I have got these two classes interacting and I am trying to call four different classes from class one for use in class two.

The methods are public and they do return va

4条回答
  •  遥遥无期
    2021-02-05 22:40

    You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

    class Example {
      public static string NonInstanceMethod() {
        return "static";
      }
      public string InstanceMethod() { 
        return "non-static";
      }
    }
    
    static void SomeMethod() {
      Console.WriteLine(Example.NonInstanceMethod());
      Console.WriteLine(Example.InstanceMethod());  // Does not compile
      Example v1 = new Example();
      Console.WriteLine(v1.InstanceMethod());
    }
    

提交回复
热议问题