Explain a statement in C#
I am working my way through a book called Head First C#. It doesnt explain what the loop is saying in detail. It would be great if someone can explain the part I dont understand. The way I am reading this is as long as c is less than 254 and visible c will increase by 1 each time the loop is gone through. What I dont understand is the (c, 255 - c, c)
private void button1_Click(object sender, EventArgs e)
{
while (Visible)
开发者_Python百科 {
for (int c = 0; c < 254 && Visible; c++)
{
this.BackColor = Color.FromArgb(c, 255 - c, c);
Application.DoEvents();
System.Threading.Thread.Sleep(5);
}
}
}
this.BackColor = Color.FromArgb(c, 255 - c, c);
The arguments to that function are red, green, blue
. The maximum value is 255 and the minimum value is 0. This function fades the color from full green into no green, full red-blue (magenta).
for (int c = 0; c < 254 && Visible; c++)
The loop will continue until either the form is made invisible (assuming this event handler is on a form, Visible
refers to this.Visible
and will be false if the form is hidden), or the maximum value is reached (c < 254
will be false).
Here's a chart that shows the common colors based on their red, green, and blue values. In the chart, the format is RRGGBB
, where RR
is the red value, GG
is the green value, and BB
is the blue value. The numbers are in hex (runs from 0 to FF instead of 0 to 255).
So it's this statement that you don't understand, right?
this.BackColor = Color.FromArgb(c, 255 - c, c);
That's setting the BackColor
property to the value returned from the Color.FromArgb
method. The arguments to that method are c
, 255 - c
, and c
. So for example, if c
is 100, it will call Color.FromArgb(100, 155, 100)
.
Basically this is animating the background colour from green (0, 255, 0) to purple (253, 2, 253). It's doing it in a pretty nasty way, using Application.DoEvents
and making the UI thread sleep, but hopefully the book will explain a nicer approach over time :)
You are correct about what will happen to 'c' as the loop iterates. The line you are having trouble with is creating a different color from the value of 'c' on each iteration. Thus, the backcolor of the form will change as c changes.
The description of the behavior is wrong.
This routine will continually slide the color from green to purple and then reset it to green and do it again. The only way the loop exits is if the button turns invisible in response to something that is executed by the DoEvents() call.
精彩评论