非静态类如何调用另一个非静态类的方法?

Dar*_*try 5 c# non-static

我有2个非静态类.我需要在一个类上访问一个方法来返回一个对象进行处理.但由于这两个类都是非静态的,我不能以静态方式调用该方法.我也不能以非静态方式调用该方法,因为程序不知道对象的标识符.

在此之前,如果可能的话,我希望两个对象尽可能保持非静态.否则,需要对其余代码进行大量重组.

下面是代码中的示例

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?
    }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ers 11

class Bar
{
    /*...*/

    public void MethodCaller()
    {
        var x = new Foo();
        object y = x.MethodToCall();
    }
}
Run Code Online (Sandbox Code Playgroud)

BTW,一般来说,对象没有名称.


das*_*ght 2

为了使静态或非静态类中的任何代码能够调用非静态方法,调用者必须拥有对进行调用的对象的引用。

就您而言,Bar'sMethodCaller必须引用Foo. 您可以通过构造函数Bar或您喜欢的任何其他方式传递它:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)