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

前端 未结 4 697
傲寒
傲寒 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 16:44

    By passing an instance to the constructor:

    class Bar
    {
        private Foo foo;
    
        public Bar(Foo foo)
        { 
            _foo = foo;
        }
    
        public void MethodCaller()
        {
            _foo.MethodToCall();
        }
    }
    

    Usage:

    Foo foo = new Foo();
    Bar bar = new Bar(foo);
    bar.MethodCaller();
    

提交回复
热议问题