What's wrong with this expression? Cannot implicitly convert type 'int' to 'byte'
I am getting the error "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists开发者_如何学Go (are you missing a cast?)". Doesn't byte + byte = byte
? Also I notice when I remove the +rgb.Green
it works
// rgb.Red, rgb.Green, rgb.Blue are byte types
// h, delta are double
rgb.Red = Convert.ToByte(Math.Round((h - 4) * delta)) + rgb.Green;
public struct RGBColor
{
public byte Red { get; set; }
public byte Green { get; set; }
public byte Blue { get; set; }
}
Adding two bytes produces an integer in C#. Convert the entire thing back to a byte.
rgb.Red = (byte)(Convert.ToByte(Math.Round((h - 4) * delta)) + rgb.Green);
See byte + byte = int... why? for more information.
Doesn't byte + byte = byte?
Nope, because it may overflow (> 255), that's why this operation returns an Int32. You could cast the result back to byte at your own risk.
http://msdn.microsoft.com/en-us/library/5bdb6693(VS.71).aspx
byte + byte = int
More accurately framework doesn't define operator + on byte, but there is an implicit conversion from byte to int, to
byte + byte = int + int = int
I don't quite agree with the justification for this being that it may overflow, since so may int + int. But obviously byte arithmetic is far more 'dangerous' in this respect - and this behaviour forces you to take a close look at what you are doing.
C# widens all operands to int
before doing arithmetic on them. So you'll need to cast it back to byte explicitly.
http://msdn.microsoft.com/en-us/library/5bdb6693(VS.80).aspx
For built-in numeric types, an implicit conversion can be made when the value to be stored can fit into the variable without being truncated or rounded off. For example, a variable of type long (8 byte integer) can store any value that an int (4 bytes on a 32-bit computer) can store.
Refer Implicit Conversion section in this https://msdn.microsoft.com/en-us/library/ms173105.aspx
Now coming to your example obviously byte + byte need not necessarily be a byte. So byte+byte may be int. In that case "Implicit Conversion" will not fit because Upward casting is possible not vice versa, that is int can be converted to long, byte can be converted to int.
So in your case you need explicit conversion. Compiler needs you to perform this.
However, if a conversion cannot be made without a risk of losing information, the compiler requires that you perform an explicit conversion, which is called a cast. A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur.
Refer explicit conversion in the same page.
so for your example
rgb.Red = (byte)(Convert.ToByte(Math.Round((h - 4) * delta)) + rgb.Green);
This will convert int to byte explicitly.
精彩评论