C # delegate for struct method

I am trying to create a delegate for the struct method for a specific instance. However, it turns out that a new instance of the structure is created, and when I call the delegate, it executes this method on top of the newly created instance, and not the original.

static void Main(string[] args) { Point A = new Point() { x = 0 }; Action move = A.MoveRight; move(); //Ax is still zero! } struct Point { public int x, y; public void MoveRight() { x++; } } 

Actually, what happens in this example is that a new instance of struct Point is created on the delegate creator, and the method that is called through delagate is executed on it.

If I use a class instead of a structure, the problem is resolved, but I want to use a struct. I also know that there is a solution with creating an open delegate and passing the structure as the first parameter to the delegate, but this solution seems too heavy. Is there any simple solution to this problem?

+4
source share
3 answers

No, there is no way around this. Do you have a specific reason to use struct ? Unless you have a special need, you really should use a class .

By the way, you created a mutable structure (a structure whose values ​​can change), which, without exaggeration, is an anathema. You must use a class.

+8
source

Variable structures are evil and should not be used! *

You can change the struct as immutable and your MovePoint method MovePoint return a new structure value:

 struct Point { private readonly int x, y; public Point(x, y) { this.x = x; this.y = y; } public struct MoveRight() { x++; } } 

Then you should use Func<Point, Point> to represent the operation that changes the point:

 Func<Point, Point> move = a => a.MoveRight; Point A = new Point() { x = 0 }; Point newA = move(A); // newA.x is 1, but Ax is still 0, because struct is immutable Point anotherA = move(newA); // move the point again... 

*) Of course, there are situations when they can be useful, but if your situation was one of them, you would not ask this question.

+6
source

Anathema or not, perhaps in office using C #. In 3D engines, we perform any diabolical work. So, for example, in the Unity3D engine, Vector3 has a structure using the Set (x, y, z) function, and you can even change x, y, z, since they are open fields. Everything for speed (for example, if you have fewer calculations for this, you will have something else for it.

  static void Main(string[] args) { Point A = new Point() { x = 0 }; MyPointDelegate<Point> move=(ref Point p)=> p.MoveRight(); move(ref A); Console.Write(Ax); //Ax is one! } public delegate void MyPointDelegate<Point>(ref Point t); struct Point { public int x, y; public void MoveRight() { x++; } } 
0
source

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


All Articles