一週學會C#(前言續)
C#才鳥(QQ:249178521)
4.標點符號<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
{ 和 } 組成語句塊
分號表示一個語句的結束
using System;
public sealed class Hiker
{
public static void <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />Main()
{
int result;
result = 9 * 6;
int thirteen;
thirteen = 13;
Console.Write(result / thirteen);
Console.Write(result % thirteen);
}
}
一個C#的“類/結構/枚舉”的定義不需要一個終止的分號。
public sealed class Hiker
{
...
} // 沒有;是正確的
然而你可以使用一個終止的分號,但對程序沒有任何影響:
public sealed class Hiker
{
...
}; //有;是可以的但不推薦
在Java中,一個函數的定義中可以有一個結尾分號,但在C#中是不允許的。
public sealed class Hiker
{
public void Hitch() { ... }; //;是不正確的
} // 沒有;是正確的
5.聲明
聲明是在一個塊中引入變量
u 每個變量有一個標識符和一個類型
u 每個變量的類型不能被改變
using System;
public sealed class Hiker
{
public static void Main()
{
int result;
result = 9 * 6;
int thirteen;
thirteen = 13;
Console.Write(result / thirteen);
Console.Write(result % thirteen);
}
}
這樣聲明一個變量是非法的:這個變量可能不會被用到。例如:
if (...)
int x = 42; //編譯時出錯
else
...
6.表達式
表達式是用來計算的!
w 每個表達式產生一個值
w 每個表達式必須只有單邊作用
w 每個變量只有被賦值後才能使用
using System;
public sealed class Hiker
{
public static void Main()
{
int result;
result = 9 * 6;
int thirteen;
thirteen = 13;
Console.Write(result / thirteen);
Console.Write(result % thirteen);
}
}
C#不允許任何一個表達式讀取變量的值,除非編譯器知道這個變量已經被初始化或已經被賦值。例如,下面的語句會導致編譯器錯誤:
int m;
if (...) {
m = 42;
}
Console.WriteLine(m);// 編譯器錯誤,因爲m有可能不會被賦值
7.取值
類型 取值 解釋
bool true false 布爾型
float 3.14 實型
double 3.1415 雙精度型
char 'X' 字符型
int 9 整型
string "Hello" 字符串
object null 對象