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

后端 未结 4 663
臣服心动
臣服心动 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:37

    It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.

    MyClass myClass = new MyClass();
    

    once you've added that line you can then call your method

    myClass.myMethod();
    

    Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

    0 讨论(0)
  • 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());
    }
    
    0 讨论(0)
  • 2021-02-05 22:44

    You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

    GradeBook myGradeBook = new GradeBook();
    

    Then call the method on the obect you just created.

    myGradeBook.[method you want called]
    
    0 讨论(0)
  • 2021-02-05 22:55

    For example 1 and 2 you need to create static methods:

    public static string InstanceMethod() {return "Hello World";}
    

    Then for example 3 you need an instance of your object to invoke the method:

    object o = new object();
    string s = o.InstanceMethod();
    
    0 讨论(0)
提交回复
热议问题