這是從 byte 轉換為 short、ushort、int、uint、long、ulong、float、double 或 decimal 之預先定義的隱含轉換。
需要較大儲存空間的非常值數字型別不能隱含轉換成 byte。如需整數類資料型別儲存空間的詳細資訊,請參閱整數類資料型別表 (C# 參考)。以下列兩個 byte 變數 x 和 y 為例:
複製程式碼
byte x = 10, y = 20;
下列指派陳述式 (Assignment Statement) 會產生編譯錯誤,因為根據預設,指派運算子右邊的算術運算式會評估為 int。
複製程式碼
// Error: conversion from int to byte:
byte z = x + y;
若要修正這個問題,請使用轉型 (Cast):
複製程式碼
// OK: explicit conversion:
byte z = (byte)(x + y);
當目的變數有相同或較大的儲存空間時,下列陳述式仍可以使用:
複製程式碼
int x = 10, y = 20;
int m = x + y;
long n = x + y;
此外也沒有從浮點型別到 byte 的隱含轉換。例如,下列陳述式必須使用明確轉換,否則會產生編譯器錯誤:
複製程式碼
// Error: no implicit conversion from double:
byte x = 3.0;
// OK: explicit conversion:
byte y = (byte)3.0;
呼叫多載方法時,必須使用轉型。以下列使用 byte 和 int 參數的多載方法為例:
複製程式碼
public static void SampleMethod(int i) {}
public static void SampleMethod(byte b) {}
使用 byte 轉型可以保證呼叫到正確的型別,例如:
複製程式碼
// Calling the method with the int parameter:
SampleMethod(5);
// Calling the method with the byte parameter:
SampleMethod((byte)5);
文章定位:
人氣(166) | 回應(0)| 推薦 (
0)| 收藏 (
0)|
轉寄
全站分類:
不分類