How to call a method in the calling class?

  • Thread starter Thread starter Lakesider
  • Start date Start date
L

Lakesider

Hi NG,

my problem is: I have a class A with a map on it. There is a public
methode "Refresh" for this map. Within A i call a class B (new B). In B
I modify some things, that would need to do a refresh in A.

My question: HOW can I call A.refresh() from B???

What is here a "best practice"?

Thank you very much

Rudi
 
My question: HOW can I call A.refresh() from B???
What is here a "best practice"?

Depends on how tightly coupled you want the A and B classes to be. You could
add a parameter of type A, pass in the this reference and then just call
Refresh on that from B. Or you could define and implement an interface (such
as IRefreshable) and use that as the parameter type. Or you could pass in a
delegate that represents just the Refresh method.


Mattias
 
Hi Lakesider,
you can pass the reference of class A to B in its constructor, then B will
be able to call A.Refresh(), like:

class A
{
public void DoSomething()
{
B bInst = new B(this);
bInst.SomeMethod();
}

public void Refresh()
{
}
}

class B
{
private A _aInst;

public B(A aInst)
{
_aInst = aInst;
}

public void SomeMethod()
{
//do work

_aInst.Refresh();
}
}

Or you could pass in a Reference to A in the method you call on B, if you
want to limit the scope of the A reference inside of B.

You could have A call Refresh on itself once it has finished calling the
method in B which updates the map values, but I wouldn't recommend this
baceause then class A needs to know what B is doing internally which is not a
good thing, it should not be A who is aware of this but rather class B.

Hope that helps
Mark R Dawson
http://www.markdawson.org
 
A simple solution like the following

public class A {

void DoSomthing() {
B b = new B();
b.DataChanged += new EventHandler(this.DataChangedHandler);
}

public void DataChangedHandler(object sender, EventArgs e) {
//refresh here
}

}

public class B {
public event EventHandler DataChanged;

public void ChangData(A a) {
//supposed to change some data
OnDataChanged(EventArgs.Empty);
}

protected void OnDataChanged(EventArgs e) {
DataChanged(this,e);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top