| 原本型態 | 會被轉換成的型態 |
|---|---|
| sbyte | short、int、long、float、double 或 decimal |
| byte | short、ushort、int、uint、long、ulong、float、double 或 decimal |
| short | int、long、float、double 或 decimal |
| ushort | int、uint、long、ulong、float、double 或 decimal |
| int | long、float、double 或 decimal |
| uint | long、ulong、float、double 或 decimal |
| long | float、double 或 decimal |
| char | ushort、int、 uint、 long、ulong、 float、 double 或 decimal |
| float | double |
| ulong | float、 double 或 decimal |
舉例如下
class Demo {
static void Main() {
byte a = 255;
System.Console.WriteLine(a + 1);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:conversion1.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */由於 byte 的最大值為 255 ,加 1 後會自動轉換成 short ,這樣保證所有資訊不會計算過程中遺失。
編譯執行,結果如下

以上是隱性的自動轉換,我們也能夠強制進行型態轉換,此時在運算式 (expression) 前加上小括弧與型態名稱即可,例如
class Demo {
static void Main() {
int a = 1;
byte b = (byte) (a + 1);
System.Console.WriteLine(b);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:conversion2.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */編譯執行,結果如下

| 中英文術語對照 | |
|---|---|
| 型態 | type |
| 運算式 | expression |
您可以繼續參考
運算式
型態轉換
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: 轉型和型別轉換 (C# 程式設計手冊)
msdn: 隱含數值轉換表 (C# 參考)
沒有留言:
張貼留言