C# 的基本語法,標識符,關鍵字(學習心得 3)
C# 是面對對象的編程。
程式由各種交互對象組成。
同種類對象,通常在相同的 class 中。
例如我們實現一個矩形對象 Rectangle 的類,那這個類下面會有 length 和 width 屬性,根據屬性計算面積和顯示細節。
實例:
using System;
// 任何 C# 程式中第一條都是這個語句
namespace RectangleApplication
//新建一個命名空間 RectangleApplication
{
class Rectangle
//新建一個類
{
// 設置變數
double length;
double width;
// 函數-變數賦值
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
}
// 函數-獲取面積
public double GetArea()
{
return length * width;
}
// 函數-顯示結果
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
// 再新建一個類用於執行程式
class ExcuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
// Rectangle 實例化
r.Acceptdetails();
// 運行類下面的方法 Acceptdetails 進行賦值
r.Display();
// 運行類的方法 Display 進行顯示結果
Console.ReadLine();
// 這個不知道是做什麼用的???
}
}
}
運行結果:
Length: 4.5
Width: 3.5
Area: 15.75
標識符
類,變數,函數,或其他項目的名字。
規則如下:
- 以字母,下劃線,@ 開頭。
- 第一個字元不能是數字。
- 不可包含空格和特殊符號。
- 不能是 C# 關鍵字。
- 大小寫敏感。
- 不能與 C# 類庫名稱相同。
C# 關鍵字
C# 編譯器預定義的保留字。
保留關鍵字 | ||||||
---|---|---|---|---|---|---|
abstract | as | base | bool | break | byte | case |
catch | char | checked | class | const | continue | decimal |
default | delegate | do | double | else | enum | event |
explicit | extern | false | finally | fixed | float | for |
foreach | goto | if | implicit | in | in (generic modifier) | int |
interface | internal | is | lock | long | namespace | new |
null | object | operator | out | out (generic modifier) | override | params |
private | protected | public | readonly | ref | return | sbyte |
sealed | short | sizeof | stackalloc | static | string | struct |
switch | this | throw | true | try | typeof | uint |
ulong | unchecked | unsafe | ushort | using | virtual | void |
volatile | while | |||||
上下文關鍵字 | ||||||
add | alias | ascending | descending | dynamic | from | get |
global | group | into | join | let | orderby | partial (type) |
partial (method) | remove | select | set |