Why does the Windows Forms Designer cast int to by

2019-02-23 00:55发布

问题:

I was looking through some code today and saw something like the following:

var colour = Color.FromArgb(((int)(((byte)(227)))), ((int)(((byte)(213)))), ((int)(((byte)(193)))));

When I asked why it was so, since Resharper confirmed that all the casts are redundant, I was told that the Designer done it that way and they had copied that.

I had a look and sure enough the Designer generates code the same as above when setting a property to a custom colour.

Does anyone know why the Designer would do this? It doesn't appear to make sense on the face of it, unless I am missing something?

回答1:

This code is auto-generated by the code serializer built into the Winforms designer. The guilty party here is the System.Drawing.ColorConverter class, the TypeConverter for Color. The relevant code in its ConvertTo() method is:

   member = typeof(Color).GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int) });
   arguments = new object[] { color2.R, color2.G, color2.B };

The R, G and B properties return a byte. So the code serializer first generates the integer literal and applies the (byte) cast to match the arguments type. Then sees that FromArgb() accepts integer arguments so applies the (int) cast.

This is just maniacal machine generated code. It only has to be correct, it doesn't have to be pretty.



回答2:

There is no benefit. All it does is make the code hard to read.

This is preferable

var colour = Color.FromArgb(227, 213, 193);

or even the alpha channel version:

var colour = Color.FromArgb(255, 227, 213, 193);

As @Alexei Levenkov points out, perhaps the author was being cautious, but given the clear name of the method and its (well known) intended use, why would anyone use a value greater then 255 for any of the parameters?

Ref. Color.FromArgb Method