C# 程式設計/語法
外觀
C# 語法看起來與 Java 的語法非常相似,因為它們都從 C 和 C++ 中繼承了大部分語法。C# 的面向物件特性要求 C# 程式的高階結構以類的形式定義,其詳細行為由其語句定義。
C# 程式中執行的基本單位是語句。語句可以宣告變數,定義表示式,透過呼叫方法執行簡單操作,控制其他語句的執行流程,建立物件,或將值分配給變數,屬性或欄位。語句通常以分號結尾。
語句可以分組到以逗號分隔的語句列表或以大括號括起來的語句塊中。
示例
int sampleVariable; // declaring a variable
sampleVariable = 5; // assigning a value
Method(); // calling an instance method
SampleClass sampleObject = new SampleClass(); // creating a new instance of a class
sampleObject.ObjectMethod(); // calling a member function of an object
// executing a "for" loop with an embedded "if" statement
for (int i = 0; i < upperLimit; i++)
{
if (SampleClass.SampleStaticMethodReturningBoolean(i))
{
sum += sampleObject.SampleMethodReturningInteger(i);
}
}
由大括號包圍的一系列語句構成一個程式碼塊。除其他目的外,程式碼塊用於限制範圍,即變數可以使用範圍。變數僅在定義它的塊中可訪問。程式碼塊可以巢狀,並且通常作為方法的主體出現。
private void MyMethod(int integerValue)
{ // This block of code is the body of "MyMethod()"
// The 'integerValue' integer parameter is accessible to everything in the method
int methodLevelVariable; // This variable is accessible to everything in the method
if (integerValue == 2)
{
// methodLevelVariable is still accessible here
int limitedVariable; // This variable is only accessible to code in the, if block
DoSomeWork(limitedVariable);
}
// limitedVariable is no longer accessible here
} // Here ends the code block for the body of "MyMethod()".
註釋允許對原始碼進行內聯文件化。C# 編譯器會忽略註釋。以下注釋風格在 C# 中是允許的。
- 單行註釋
- 字元序列
//將後續文字標記為單行註釋。單行註釋,顧名思義,在//註釋標記後的第一個行尾處結束。 - 多行註釋
- 註釋可以透過使用多行註釋風格跨越多行。此類註釋以
/*開始,以*/結束。這些多行註釋標記之間的文字就是註釋。
// This style of a comment is restricted to one line.
/*
This is another style of a comment.
It allows multiple lines.
*/
- XML 文件行註釋
- 這些註釋用於生成 XML 文件。可以使用單行和多行風格。單行風格,其中每行註釋都以
///開頭,比以/**和*/分隔的多行風格更常見。
/// <summary> documentation here </summary>
/// <remarks>
/// This uses single-line style XML Documentation comments.
/// </remarks>
/**
* <summary> documentation here </summary>
* <remarks>
* This uses multiple-line style XML Documentation comments.
* </remarks>
*/
C# 是大小寫敏感的,包括其變數和方法名稱。
下面型別為int 的變數myInteger 和MyInteger 是不同的,因為 C# 是大小寫敏感的。
int myInteger = 3;
int MyInteger = 5;
例如,C# 定義了一個類Console 來處理大多數與控制檯視窗的操作。除非之前定義了一個名為console 的物件,否則編寫以下程式碼會導致編譯器錯誤。
// Compiler error!
console.writeline("Hello");
以下更正後的程式碼按預期編譯,因為它使用了正確的大小寫。
Console.WriteLine("Hello");