Exit parameter (link) with action <>

I have many methods like this:

  void GetColorSky(out float r, out float g, out float b) void GetColorGround(out float r, out float g, out float b) 

β€œLike” means that they have the same method header excluding the method name. I also have several colourPicker controls that take values ​​of R, G, B.

I am trying to create a method that takes a method as one of its parameters, for example:

 UpdateColourPicker(ColorPicker cp, CustomMethod cMethod) 

and name it as follows:

 UpdateColourPicker(cpSky, GetColorSky) UpdateColourPicker(cpGround, GetColorGround) 

What is the correct syntax for out and Action together? I looked through this question , but I still failed.

Thanks!

+6
source share
2 answers

Taking the answer from this related answer, this will work:

 public delegate void GetColorDel(out float r, out float g, out float b); void UpdateColourPicker(ColorPicker cp, GetColorDel cMethod) { } UpdateColourPicker(cpSky, GetColorSky); UpdateColourPicker(cpGround, GetColorGround); 

Unfortunately, as indicated in the answer to your question, Action and Func do not work with out and ref . This is simply because Action and Func are just delegate definitions (quite a few times to offer different overloads) with generics in BCL. Adding ref and out options will quickly cause override compiler errors.

Full sample:

 class Program { public delegate void GetColorDel(out float r, out float g, out float b); static void Main(string[] args) { UpdateColourPicker(null, GetColorSky); UpdateColourPicker(null, GetColorGround); Console.Read(); } static void GetColorSky(out float r, out float g, out float b) { r = g = b = 0f; Console.WriteLine("sky"); } static void GetColorGround(out float r, out float g, out float b) { r = g = b = 0f; Console.WriteLine("ground"); } static void UpdateColourPicker(object cp, GetColorDel cMethod) { float r, g, b; cMethod(out r, out g, out b); } } 
+3
source

If you want to define a common delegate with out parameters, this should be done as follows:

 delegate void ActionWithOutparameter<T>(out T x); delegate void ActionWithOutparameter<T1, T2>(out T1 x, out T2 y); // ... 

Obviously, the Action and Func delegates in the BCL do not match this signature.

+1
source

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


All Articles