共用方式為


內建資料型別 (Visual C# Express)

更新:2007 年 11 月

C# 是一種強型別 (Strongly Typed) 語言。在值可以儲存在變數中之前,必須先指定變數的型別,如下範例所示:

int a = 1;
string s = "Hello";
XmlDocument tempDocument = new XmlDocument();

請注意,不論簡單的內建型別 (例如 int) 或是複雜或自訂型別 (例如 XmlDocument) 都必須予以指定。

C# 支援下列內建資料型別:

資料型別

範圍

byte

0 .. 255

sbyte

-128 .. 127

short

-32,768 .. 32,767

ushort

0 .. 65,535

int

-2,147,483,648 .. 2,147,483,647

uint

0 .. 4,294,967,295

long

-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807

ulong

0 .. 18,446,744,073,709,551,615

float

-3.402823e38 ..3.402823e38

double

-1.79769313486232e308 ..1.79769313486232e308

decimal

-79228162514264337593543950335 .. 79228162514264337593543950335

char

Unicode 字元

string

Unicode 字元字串

bool

True 或 False

object

物件

這些資料型別名稱是 System 命名空間中預先定義的型別別名。這些型別列於章節:內建型別資料表 (C# 參考)。除了物件和字串以外,所有型別都是實值型別。如需詳細資訊,請參閱實值和參考型別 (Visual C# Express)

使用內建資料型別

在 C# 程式中有幾種使用內建資料型別的方式。

當做變數:

int answer = 42;
string greeting = "Hello, World!";

當做常數:

const int speedLimit = 55;
const double pi = 3.14159265358979323846264338327950;

當做傳回值和參數:

long CalculateSum(int a, int b)
{
    long result = a + b;
    return result;
}

若要定義自己的資料型別,請使用類別 (Visual C# Express)列舉型別 (Visual C# Express)結構 (Visual C# Express)

轉換資料型別

資料型別的轉換可以隱含地完成 (由編譯器自動完成轉換),或是使用轉換 (Cast) 明確地完成 (由程式設計人員強制轉換,並且負擔遺失資訊的風險)。

例如:

int i = 0;
double d = 0;

i = 10;
d = i;        // An implicit conversion

d = 3.5;
i = (int) d;  // An explicit conversion, or "cast"

請參閱

概念

C# 語言入門

變數與常數 (Visual C# Express)

參考

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

其他資源

格式化數值結果表 (C# 參考)