为什么Windows Forms Designer将FromArgb的int转换为int然后返回int? [英] Why does the Windows Forms Designer cast int to byte then back to int for FromArgb?

查看:62
本文介绍了为什么Windows Forms Designer将FromArgb的int转换为int然后返回int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天正在浏览一些代码,看到的内容如下:

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)))));

当我问为什么这样时,由于Resharper确认所有演员都是多余的,所以我被告知

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.

我看了一下,确信将属性设置为自定义时,Designer生成的代码与上述相同。

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?

推荐答案

此代码是自动的,由Winforms设计器中内置的代码序列化程序生成。有罪的一方是System.Drawing.ColorConverter类,即Color的TypeConverter。其ConvertTo()方法中的相关代码为:

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 };

R,G和B属性返回一个字节。因此,代码序列化程序首先生成整数文字,并应用(byte)强制转换以匹配参数类型。然后看到FromArgb()接受整数参数,因此应用(int)强制转换。

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.

这篇关于为什么Windows Forms Designer将FromArgb的int转换为int然后返回int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆