If we have a Class
public class A
{
public void resetValues()
{
//DoSomething
}
B b = new B();
}
public class B
{
public B()
{
}
void doSomething()
{
//Is there a way here to call A(the Creator) method resetValues();
//Like Creator.resetValues();
}
}
So is there a way to call the Creator methods like in this Example Class A method's . This is is very needful when i use a Form to show Another Form : from FormA
FormB frmB = new FormB();
frmB.Show();
this.hide();
Than i should onFormClose
Event of FormB to Show again the FormA
EDIT First i thought parsing A by Ref as Object ,but Storing a Reference as a Field later i founded out that's impossible !
First i thought 开发者_开发问答maybe using reflection we can Identify and Call Creator method's but i think i mismatched some of OOP Design Pattern's
The only way is to pass in the "creator" when calling the constructor:
B b = new B(this);
Of course, that means that B
needs to have a constructor with the appropriate parameter type, which should match whatever it needs to do with its creator.
EDIT: As noted in comments, it doesn't really need to be done at construction - it could be a property:
B b = new B();
b.Creator = this;
They amount to basically the same thing though.
I would suggest this is usually a bad idea, to be honest. It's introducing a reasonably tight coupling between the two classes. It might be better for B
to publish an event which the creator can subscribe to, in order to handle appropriate state changes etc on B
.
Following on from @Jon Skeet's answer, it would be preferable for class B to emit an event when something happens and for class A to consume that event.
In this way, class B has no dependency on class A. You could reuse class B with classes other than class A without modifying the internals of class B. From a maintenance POV, this is far more preferable.
You could set it up as follows:
public class A
{
B b = new B();
public A()
{
b.SomethingHappened += SomethingHappenedHandler;
}
public void resetValues()
{
//DoSomething
}
public void SomethingHappenedHandler(object sender, EventArgs args)
{
resetValues();
}
}
and
public class B
{
public event EventHandler SomethingHappened;
public B()
{
}
void doSomething()
{
var ev = SomethingHappened;
if(ev != null)
{
ev(this, EventArgs.Empty);
}
}
}
You can use simply Action
instead Func<bool>
, returning bool allows passing back a state which indicating whether operation was executed successfully.
class B
{
private Func<bool> executeExternal;
public B(Func<bool> executeExternal)
{
this.executeExternal= executeExternal;
// here is resetValues() will be executed in case of B class
bool isDoneSuccessfully = this.executeExternal();
}
}
public class A
{
public void resetValues()
{
//DoSomething
}
// basically we injecting a delegate
B b = new B(() => { this.resetValues(); return true; } );
}
精彩评论