我有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?
}
}
为了使静态或非静态类中的任何代码都可以调用非静态方法,调用者必须具有对其进行调用的对象的引用。
在你的情况,Bar
的MethodCaller
必须有一个参考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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句