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

余生长醉 提交于 2019-12-01 17:16:53

问题


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



来源:https://stackoverflow.com/questions/9073554/why-does-the-windows-forms-designer-cast-int-to-byte-then-back-to-int-for-fromar

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