How can a non-static class call another method of the non-static class?

I have 2 non-static classes. I need to access a method on one class in order to return an object for processing. But since both classes are non-static, I can't just call the method in a static way. Also, you cannot call the method in a non-stationary way, because the program does not know the identifier of the object.

Before anything, if possible, I would like both objects to remain unstable, if possible. Otherwise, a major restructuring of the rest of the code would be required.

Here is a sample code

class Foo { Bar b1 = new Bar(); public object MethodToCall(){ /*Method body here*/ } } Class Bar { public Bar() { /*Constructor here*/ } public void MethodCaller() { //How can i call MethodToCall() from here? } } 
+5
source share
4 answers

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

In your case, the Bar MethodCaller should have a link to Foo . You can pass it in the constructor of Bar or in any other way that 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(); } } 
+2
source
 class Bar { /*...*/ public void MethodCaller() { var x = new Foo(); object y = x.MethodToCall(); } } 

By the way, objects have no names.

+11
source

Passing an instance to the constructor:

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

Using:

 Foo foo = new Foo(); Bar bar = new Bar(foo); bar.MethodCaller(); 
+2
source

Try the following:

 class Foo { public Foo() { /*Constructor here*/ } Bar b1 = new Bar(); public object MethodToCall(){ /*Method body here*/ } } Class Bar { public Bar() { /*Constructor here*/ } Foo f1 = new Foo(); public void MethodCaller() { f1.MethodToCall(); } } 
0
source

Source: https://habr.com/ru/post/1209118/


All Articles