1。4 預定義類型(Predefined types)
c#提供了一系列預定義類型。它們與c/c++有不少相似的地方。預定義引用類型有object和string。object類型是所有其他類型的基礎。
預定義類型包括符號數、無符號數、浮點、布爾、字符和十進制數。符號數有:
sbyte、short、
int和long;
無符號數有:byte、ushort、uint和ulong;
浮點數有:float和double。
布爾類型就像一個開關,只有兩種狀態:true或false。c#對布爾的要求比c/c++嚴格,與java類似。
在c#中false不等於0,true也不等於1;false和true都是單獨分離出來的一個值。學過c/c++的網友都知道:
*/
int i = 0;
if (i = 0) { // Bug: 應該是 (i == 0)
....
}
/*
是沒有問題的。但在c#中會引發一個編譯錯誤(error CS0029: Cannot implicitly converttype int to bool)。當然,這樣犧牲了一點沒有必要的靈活性。我們再也不能這樣:
*/
string str;
....
if(str = Console.ReadLine()) {
Console.WriteLine("Your comments are: {0}",str);
....
/*
而必須:
*/
using System;
class BoolTest
{
static void Main() {
string str = Console.ReadLine();//也可以:string str;
if(str == "") // if((str = Console.ReadLine()) == "")
Console.WriteLine("i cant read your comments. Please tell me something! O.K.?");
else
Console.WriteLine("Your comments are: {0}",str);
}
}
/*
抄了一張預定義類型的簡表供大家參考。
Type Description Examples
object The ultimate base type of all other types object o = new Stack();
string String type; a string is a sequence of string s = "Hello";
Unicode characters
sbyte 8-bit signed integral type sbyte val = 12;
short 16-bit signed integral type short val = 12;
int 32-bit signed integral type int val = 12;
long 64-bit signed integral type long val1 = 12;
long val2 = 34L;
byte 8-bit unsigned integral type byte val1 = 12;
byte val2 = 34U;
ushort 16-bit unsigned integral type ushort val1 = 12;
ushort val2 = 34U;
uint 32-bit unsigned integral type uint val1 = 12;
uint val2 = 34U;
ulong 64-bit unsigned integral type ulong val1 = 12;
ulong val2 = 34U;
ulong val3 = 56L;
ulong val4 = 78UL;
float Single-precision floating point type float value = 1.23F;
double Double-precision floating point type double val1 = 1.23
double val2 = 4.56D;
bool Boolean type; a bool value is either bool value = true;
true or false
char Character type; a char value is a Unicode char value = h;
character
decimal Precise decimal type with 28 significant digits decimal value = 1.23M;
你也可以自定義自己的預定義類型,可以這樣:
*/
using System;
struct Digit
{...}
class Test
{
static void TestInt() {
int a = 1;
int b = 2;
int c = a + b;
Console.WriteLine(c);
}
static void TestDigit() {
Digit a = (Digit) 1;
Digit b = (Digit) 2;
Digit c = a + b;
Console.WriteLine(c);
}
static void Main() {
TestInt();
TestDigit();
}
}
/*
這一節有點沉悶。:(