There is a class A in which the variables k, k2, kn are declared. You must pass a delegate to this class with code that interacts with class A variables. Class B is used for this. The problem is that class A is not visible from the delegate code inside class B, and such code cannot be passed to the class. How to decide if resolved at all possible?

class A { public int k; public int k2; ... public in kn; public delegate void Delegate1(); private Delegate1 Delegate; public A(Delegate1 GiveDelegate) { this.Delegate = GiveDelegate; this.Delegate(); } } class B { // ΠΊΠΎΠ΄ класса B public void interactWithA(int GiveInt) { A Test = new A(delegate(){ k = GiveInt; //мноТСство дСйствий с ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½Ρ‹ΠΌΠΈ }); } // ΠΊΠΎΠ΄ класса B } 
  • I would create an event in class B and pass class B to the constructor of class A And in class А signed up as a delegate to a class B event. If so delegates are necessary. Or use the public void SetK(int newK){k=newK;} method public void SetK(int newK){k=newK;} - Dmitry Chistik
  • @Dmitry Chistik, slightly corrected the question, unfortunately these options are not suitable. - Rubikoid

1 answer 1

You can, for example, pass this variable as an input parameter.

 class A { int k; public delegate void UpdateIntDelegate(ref int n); UpdateIntDelegate updater; public A(UpdateIntDelegate updater) { this.updater = updater; this.updater(ref k); } } class B { public B(int v) { A a = new A((ref int k) => k = v); } } 

Addition

If for some reason you need a lot of individual variables, you can just pass them all as separate parameters. But a large number of fields in the class means most likely problems with the design.

Perhaps you really need an array of data, then you can pass an array to the input of the delegate instead of a single number.

Solutions with opening write access to the fields are likely to break encapsulation, so I would not recommend this way.

  • Can we immediately transfer the entire object A ? - Grundy
  • @Grundy: No, for object A field can be (that is, should be) private. - VladD
  • In this case, only one variable. In real life, there are more. - Rubikoid
  • @VladD, well, this is decided by some thread of the protected-internal setters - Grundy
  • 2
    @Rubikoid: Then formulate the question so that it is clear in advance what your real problem is. - VladD