简体   繁体   English

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

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

I have 2 classes both non-static. 我有2个非静态类。 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?
    }
}
class Bar
{
    /*...*/

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

BTW, in general, objects don't have names. 顺便说一句,通常,对象没有名称。

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

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 . 在您的情况下, BarMethodCaller必须具有对Foo的引用。 You could pass it in a constructor of Bar or in any other way you like: 您可以在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();
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM