How can a non-static class call another non-static class's method?

前端 未结 4 699
傲寒
傲寒 2021-01-18 16:23

I have 2 classes both non-static. I need to access a method on one class to return an object for processing. But since both classes is non-static, I cant just call the metho

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 17:00

    In order for any code in a static or a non-static class to call a non-static method, the caller must have a reference to the object on which the call is made.

    In your case, Bar's MethodCaller must have a reference to Foo. You could pass it in a constructor of Bar or in any other way you like:

    class Foo
    {
        Bar b1 = new Bar(this);
    
        public object MethodToCall(){ /*Method body here*/ }
    }
    
    Class Bar
    {
        private readonly Foo foo;
    
        public Bar(Foo foo) {
            // Save a reference to Foo so that we could use it later
            this.foo = foo;
        }
    
        public void MethodCaller()
        {
            // Now that we have a reference to Foo, we can use it to make a call
            foo.MethodToCall();
        }
    }
    

提交回复
热议问题