Pergunta

I have a question how to design the following case in a good (better) model (I'm using C#): So far it is like this:

 public class ExampleClass
 {

    private object ExampleClassPrivate;
    public SubExampleClass SubExampleClassPublic;

    -------

    public void ChangeExampleClassPrivate()
    {
        ExampleClassPrivate = "SOMETHING";
    }

    private class SubExampleClass
    {
        private object SubExampleClassPrivate;
        public SubSubExampleClass SubSubExampleClassPublic;
        .
        .
        .
    }

    public class SubSubExampleClass
    {
         ...

         public void DoSomething()
         {
         //Do something within SubSubExampleClass
         //In the end: call ChangeExampleClassPrivate()
         }
    }
 }

I could do the following: I create an instance of ExampleClass, let's call it "TestInstance". Then:

TestInstance.SubExampleClassPublic.SubSubExampleClassPublic.DoSomething();
TestInstance.ChangeExampleClassPrivate();

But I don't want to execute ChangeExampleClassPrivate() manually the whole time after DoSomething(). I look for a possibility to call ChangeExampleClassPrivate() from inside of DoSomething().

How could I achieve this? I guess my class structure is not perfect, but i don't see how I could change it to work the proper way.

Foi útil?

Solução

You can pass a reference to a prent class to all your subclasses, like this:

private class SubExampleClass
{
     private object SubExampleClassPrivate;
     private readonly SubSubExampleClass SubSubExampleClassPublic;

     private readonly ExampleClass parent;

     public SubExampleClass(ExampleClass parent)
     {
         // save reference to the parent object
         this.parent = parent; 

         // pass it to subclass
         SubSubExampleClassPublic= new SubSubExampleClass(parent)
     }

    .
    .
    .
}

public class SubSubExampleClass
{
     private readonly ExampleClass parent;

     public SubSubExampleClass(ExampleClass parent)
     {
         this.parent = parent; // save reference to the parent object
     }

     public void DoSomething()
     {
         //Do something within SubSubExampleClass
         parent.ChangeExampleClassPrivate;
     }
}

And a usage, somewhere in ExampleClass:

var instance = new SubExampleClass(this);
instance.SubSubExampleClassPublic.DoSomething();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top