Why does the Windows Forms Designer cast int to byte then back to int for FromArgb?

六月ゝ 毕业季﹏ 提交于 2019-12-01 17:57:39

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!