bool myBool = true;
byte myByte;
myByte = Convert.ToByte(myBool);
myByte = (byte)myBool;
For a newbie( me
): why are the above different?
Convert.ToByte
is a method - it can do whatever it wants to, probably along the lines of:
return input ? (byte) 1 : (byte) 0;
A cast is a language-level operation. It requires that either the language knows about the conversion itself, or that one of the types involved has a user-defined conversion with the right input and output types. Neither of these is the case when converting from bool
to byte
.
Basically, the language doesn't define what that cast should mean, so the compiler prohibits it.
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.