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

纵饮孤独 提交于 2019-12-30 21:37:13

问题


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 method in a static manner. Neither can I call the method in a non-static way because the program doesnt know the identifier of the object.

Before anything, if possible, i would wish both objects to remain non-static if possible. Otherwise it would require much restructuring of the rest of the code.

Heres the example in 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?
    }
}

回答1:


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();
    }
}



回答2:


class Bar
{
    /*...*/

    public void MethodCaller()
    {
        var x = new Foo();
        object y = x.MethodToCall();
    }
}

BTW, in general, objects don't have names.




回答3:


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();



回答4:


Try this:

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();
    }
}


来源:https://stackoverflow.com/questions/27487296/how-can-a-non-static-class-call-another-non-static-classs-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!