Base base () constructor and pass this

I am trying to implement good design patterns for the program I am writing. I have such a class structure.

abstract class SomeBase
{
     public SomeObject obj { get; protected set; } 

     protected SomeBase(SomeObject x)
     {
           obj = x;
     }

     //Other methods and fields...
}

public class SomeDerived : SomeBase
{

     public SomeDerived() : base(new SomeObject(this))
     {

     }

}

Now, since I am sure that you are now, you cannot pass this to the contructor because the object was not initialized. But I really hoped this was a workaround. This is not the best practice for me to allow SomeDerived () to handle the setting of the base class field. I would like to pass this new object to the chain.

Any ideas?

+3
source share
3 answers

This is not possible, use the Init method after the constructor:

 abstract class SomeBase
 {
      private SomeObject _obj { get; set; } 
      public SomeObject obj 
      {
           get 
           {    // check _obj is inited:
                if (_obj == null) throw new <exception of your choice> ;
                return _obj;
           } 
      }

      protected SomeBase()
      {
           obj = null;
      }

      protected void Init()
      {
           obj = x;
      }

      //Other methods and fields...
 }

 public class SomeDerived : SomeBase
 {

      public SomeDerived() : base()
      {
           Init(new SomeObject(this));
      }

 }
+4

, , .

abstract class SomeBase
{
    public SomeObject obj { get; protected set; }

    protected SomeBase()
    {
        obj = (SomeObject)Activator.CreateInstance(typeof(SomeObject), this); // "this" here is SomeDerived object
    }
}

class SomeDerived : SomeBase
{
    public SomeDerived()
    {
    }
}

class SomeObject
{
    public SomeObject(SomeDerived obj)
    {
        if (obj.obj == null)
        {
            // You have the reference to SomeDerived here
            // But its properties are not yet initialized (both SomeDerived and SomeBase constructors are in the progress of execution)
            // So you should not access them in the SomeObject class constructor
        }
    }
}
0

1) - , - , - .

2) " " , - (!!!), , SomeObject "this"

, "", 2 - . "", ... .. ...

u , obj u

public abstract class MyClass{
     private SomeObject _obj ; 
     public SomeObject Obj {get { return  _obj ?? (_obj = InitializeObj() );}} //no setter needed
     protected abstract SomeObject InitializeObj();
}

public class MyRealClass:MyClass {
    protected override SomeObject InitializeObj(){
        return new VerySpecialSomeObject(this, other, another, 1, 2 , false, option: new Options());
    }   
}

For your example, such a solution provides a single "template" that wins - "polymorphism")) and receives an additional bonus - if "Obj" is not useful, it will never be created))))

-2
source

Source: https://habr.com/ru/post/1692739/


All Articles