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

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

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

在你的情况下, BarMethodCaller必须引用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(); } } 
 class Bar { /*...*/ public void MethodCaller() { var x = new Foo(); object y = x.MethodToCall(); } } 

顺便说一句,BTW,通常,对象没有名称。

通过将实例传递给构造函数:

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

用法:

 Foo foo = new Foo(); Bar bar = new Bar(foo); bar.MethodCaller(); 

试试这个:

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