I have many methods similar to this:
void GetColorSky(out float r, out float g, out float b)
void GetColorGround(out float r, out float g, out float b)
"Similar" meaning they have the exact same method header excluding the method name. I also have several "colourPicker" controls, that accept R, G, B values.
I am trying to create a method that accepts a method as one of it's parameters, like so:
UpdateColourPicker(ColorPicker cp, CustomMethod cMethod)
and call it as follows:
UpdateColourPicker(cpSky, GetColorSky)
UpdateColourPicker(cpGround, GetColorGround)
What is the correct syntax for out
and Action
together? I've looked at this question but I still haven't managed.
Thanks!
Taking cue from that linked 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 stated in the answer to the question you link, Action
and Func
do not work with out
and ref
. This is simply because Action
and Func
are just delegate definitions stated (quite a few times to offer different overloads) with generics in the BCL. Adding ref
and out
variants would quickly cause re-definition compiler errors.
The 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);
}
}
If you want to define a generic delegate with out parameters, it should be done like this:
delegate void ActionWithOutparameter<T>(out T x);
delegate void ActionWithOutparameter<T1, T2>(out T1 x, out T2 y);
// ...
Clearly the Action
and Func
delegates in the BCL do not match this signature.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.