简体   繁体   中英

How to do this without unchecked?

a few months ago I wrote this code because it was the only way I could think to do it(while learning C#), well. How would you do it? Is unchecked the proper way of doing this?

unchecked //FromArgb takes a 32 bit value, though says it's signed. Which colors shouldn't be.
{
  _EditControl.BackColor = System.Drawing.Color.FromArgb((int)0xFFCCCCCC);
}

It takes a signed int b/c this dates back to the time when VB.NET didn't have unsigned values. So in order to maintain compatibility between C# and VB.NET, all the BCL libraries utilize signed values, even if it does not make logical sense.

您可以分解int的组件并使用FromArgb()重载来分别获取它们:

System.Drawing.Color.FromArgb( 0xFF, 0xCC, 0xCC, 0xCC);

Extension methods can hide this:

public static Color ToColor(this uint argb)
{
    return Color.FromArgb(unchecked((int)argb));
}

public static Color ToColor(this int argb)
{
    return Color.FromArgb(argb);
}

Usage:

0xff112233.ToColor(); 
0x7f112233.ToColor();

Seems like they're should be another notation (like 0v12345678) or some other way to work around this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM