Delegation of a call in the constructor

I faced an easily solved, but design problem, which I had not yet encountered in my young life.

I have a class that needs to go through several setup procedures before anything else happens.

However, during the construction of this class, I have a delegate in the constructor settings, which can be passed so that the user can add his own information to the class.

When this is called, however, the scope that creates the class still does not have a valid instance, and therefore an error occurs with a null exception.

How do I get around this? Should I pass an instance of "this" to this delegate?

What a good decision to make here? I have a "StartServices ()" method, where I could easily pass the call to the delegate, but I believe that its design should be in the constructor.

Thanks for the advice!

+3
source share
5 answers

It looks like you want to pass Action<T>(or similar), so at any point where the class wants to delegate, it can call theDelegate(this); eg:

var instance = new SomeType(..., obj => { /* extra code invovling obj */ });

Then it objwill be an instance when it is created, and has the advantage that the method created by the compiler does not require any state / capture (if you do not need it).

! , virtual - ( ) , .

+6

factory:

public class MyClass
{
    private MyClass() {}

    public static MyClass Create(delegate d ...)
    {
        var instance = new MyClass();
        d.(instance);
        return instance;
    }
}

:

var o = MyClass.Create(...);

factory:

var o = factory.CreateMyClass(...);
+4

. , . .

Factory pattern , . -.

(object-) . constroctur SingelResponsibilityPrinciple .

+3

, , , , . . , " ". , , , , . , . , ( , ).

+2

, ?

, .

0

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


All Articles