C # passing the current object to another object?

I am creating an object that has such a constuctor ...

public class BusinessLogic()
{

     public BusinessLogic()
      {

           BusinessLogicSubClass blsc = new BusinessLogicSubClass(and I want to pass in BusinessLogic here)
      }
}

I do this because I want BusinessLogicSubClass to return to various methods in BusinessLogic when it completes a method. BusinessLogicSubClass also uses constructor injection to make my device tests work with NMock2.

Any suggestions here would be helpful, thanks in advance!

+3
source share
8 answers
 public BusinessLogic()
  {
       BusinessLogicSubClass blsc = new BusinessLogicSubClass(this);
  }

An alternative to this (for accessing Jon Skeet comments) would be to have a constructor and initializer that uses the "this" pointer:

public class BusinessLogic 
{
    private BusinessLogicSubClass blsc = null;

    public BusinessLogic() {}

    public void Initialize()
    {
        blsc = new BusinessLogicSubClass(this);
    }
}

public class Implementor
{
    public void SomeFunction()
    {
        BusinessLogic bl = new BusinessLogic();
        bl.Initialize();
    }
}
+5
source

this . , , , , .

, , , , . , ?

+6

, BusinessLogicSubClass, , BusinessLogic ? , . .

public class BusinessLogic {

    private BusinessLogicSubClass mChild;

    public BusinessLogic() {
    }

    public BusinessLogicSubClass Child {
        get {
            return mChild ?? (mChild = new BusinessLogicSubClass(this));
        }
    }

    public class BusinessLogicSubClass {
        public BusinessLogicSubClass(BusinessLogic parent) {
        }
    }
}

, this , , , .

+1

, , . , .

public class BusinessLogic()
{

     public BusinessLogic()
      {

           BusinessLogicSubClass blsc = new BusinessLogicSubClass(this)
      }
}
0

, - :

public class BusinessTest
{
    private BusinessSubTest aSub;

    public BusinessTest()
    {
        aSub = new BusinessSubTest(this);
    }

}

public class BusinessSubTest
{
    public BusinessSubTest(BusinessTest aTest)
    {

    }    
}

?

0

"this",

public BusinessLogic()
{
    BusinesLogicSubClass blsc = new BusinessLogicSubClass(this);
}
0

, BusinessLogic, BusinesLogicSubClass, BusinessLogic constuctor.

BusinessLogic BusinesLogicSubClass?

...

public class BusinessLogic
{
    private BusinessLogicSubClass subClass;

    private BusinessLogic()
    {
    }

    public static BusinessLogic CreateBusinessLogic()
    {
        BusinessLogic bl = new BusinessLogic();
        BusinessLogicSubClass blsc = new BusinessLogicSubClass(bl);

        bl.subClass = blsc;
        return bl;
    }
}

, , - , ...

BusinessLogic bl = BusinessLogic.CreateBusinessLogic();
0

, . , .

Initialize , , .

, , . , - , ? ( -, ? , , . .

Si Keep, , . , .

. , Stack Overflow, , . :)

0

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


All Articles