非静态类如何调用另一个非静态类的方法? [英] How can a non-static class call another non-static class's method?

查看:65
本文介绍了非静态类如何调用另一个非静态类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

在此示例代码

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?
    }
}

推荐答案

为使静态或非静态类中的任何代码调用非静态方法,调用者都必须引用其上的对象打电话了.

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.

在您的情况下, Bar MethodCaller 必须具有对 Foo 的引用.您可以在 Bar 的构造函数中传递它,也可以通过其他任何方式传递它:

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

这篇关于非静态类如何调用另一个非静态类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆