Share via


byte (C# 參考)

更新:2007 年 11 月

byte 關鍵字代表一種整數型別,可儲存的值如下表所示。

型別

範圍

大小

.NET Framework 型別

byte

0 至 255

不帶正負號的 8 位元整數

System.Byte

常值

您可以如下列範例同時宣告和初始化 byte 變數:

byte myByte = 255;

在上述宣告裡,整數常值 255 隱含地從 int 轉換成 byte。如果整數常值超過 byte 的範圍,則會發生編譯錯誤。

轉換

這是從 byte 轉換為 shortushortintuintlongulongfloatdoubledecimal 之預先定義的隱含轉換。

需要較大儲存空間的非常值數字型別不能隱含轉換成 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);

如需混合浮點型別和整數型別之算術運算式的詳細資訊,請參閱 floatdouble

如需隱含數字轉換規則的詳細資訊,請參閱隱含數值轉換表 (C# 參考)

C# 語言規格

如需詳細資料,請參閱 C# 語言規格中的下列章節:

  • 1.3 型別和變數

  • 4.1.5 整數類資料型別

請參閱

概念

C# 程式設計手冊

參考

C# 關鍵字

整數類資料型別表 (C# 參考)

內建型別資料表 (C# 參考)

隱含數值轉換表 (C# 參考)

明確數值轉換表 (C# 參考)

Byte

其他資源

C# 參考