下面通過一段代碼給大家解析C#語句的順序不同所執行的結果不一樣。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { /// <summary> /// 自定義類,封裝加數和被加數屬性 /// </summary> class MyClass { private int x = ; //定義int型變量,作為加數 private int y = ; //定義int型變量,作為被加數 /// <summary> /// 加數 /// </summary> public int X { get { return x; } set { x = value; } } /// <summary> /// 被加數 /// </summary> public int Y { get { return y; } set { y = value; } } /// <summary> /// 求和 /// </summary> /// <returns>加法運算和</returns> public int Add() { return X + Y; } } class Program { static void Main(string[] args) { MyClass myclass = new MyClass(); //實例化MyClass的對象 myclass.X = ; //為MyClass類中的屬性賦值 myclass.Y = ; //為MyClass類中的屬性賦值 int kg = myclass.Add(); Console.WriteLine(kg); //調用MyClass類中的Add方法求和 Console.ReadLine(); } } }
第60行的語句若是被放到第56行,則結果輸出是0不是8,所以,在設計程序時,要注意語句次序,有著清晰的思維邏輯 。
下面還有點時間,接著給大家介紹C#中循環語句總結
通過使用循環語句可以創建循環。 循環語句導致嵌入語句根據循環終止條件多次執行。 除非遇到跳轉語句,否則這些語句將按順序執行。
C#循環語句中使用下列關鍵字:
? do...while
? for
? foreach...in
? while
do...while
do...while語句執行一個語句或語句重復,直到指定的表達式的計算結果為false, 循環的身體必須括在大括號內{},while條件后面使用分號結尾
示例
下面的示例 實現do-while循環語句的執行
public class TestDoWhile { static void Main () { int x = 0; do { Console.WriteLine(x); x++; } while (x < 10); }}/*
Output:
0
1
2
3
4
5
6
7
8
9
*/
do-while循環在計算條件表達式之前將執行一次,如果 while表達式計算結果為 true,則,執行將繼續在第一個語句中循環。 如果表達式計算結果為 false,則會繼續從 do-while 循環后的第一個語句執行。
do-while 循環還可以通過break、goto、return 或 throw 語句退出。
for
for 循環重復執行一個語句或語句塊,直到指定的表達式計算為 false 值。 for 循環對于循環數組和順序處理很有用。
示例
在下面的示例中,int i 的值將寫入控制臺,并且 i 在每次通過循環時都加 1。
class ForTest { static void Main() { for (int i = 1; i <= 10; i++) { Console.WriteLine(i); } }}/*
Output:
1
2
3
4
5
6
7
8
9
10
*/
for 語句重復執行括起來的語句,如下所述:
? 首先,計算變量 i 的初始值。
? 然后,只要 i 的值小于或等于 10,條件計算結果就為 true。此時,將執行 Console.WriteLine 語句并重新計算 i。
? 當 i 大于10 時,條件變成 false 并且控制傳遞到循環外部。
由于條件表達式的測試發生在循環執行之前,因此 for 語句可能執行零次或多次??梢酝ㄟ^使用break、goto 、 throw或return語句退出該循環。
所有表達式的 for語句是可選的例如對于下面的語句用于寫一個無限循環。
for (; ; ){ // ...}
foreach...in
foreach 語句對實現 System.Collections.IEnumerable 或 System.Collections.Generic.IEnumerable<T>接口的數組或對象集合中的每個元素重復一組嵌入式語句。 foreach 語句用于循環訪問集合,以獲取您需要的信息,但不能用于在源集合中添加或移除項,否則可能產生不可預知的副作用。 如果需要在源集合中添加或移除項,請使用 for循環。
嵌入語句為數組或集合中的每個元素繼續執行。 當為集合中的所有元素完成循環后,控制傳遞給 foreach 塊之后的下一個語句。
可以在 foreach 塊的任何點使用 break 關鍵字跳出循環,或使用 continue 關鍵字進入循環的下一輪循環。
foreach 循環還可以通過 break、goto、return 或 throw 語句退出。
示例
在此示例中,使用 foreach 顯示整數數組的內容。
class ForEachTest { static void Main(string[] args) { int[] barray = new int[] { 0, 1, 2, 3, 4, 5}; foreach (int i in barray) { System.Console.WriteLine(i); } } } /*
Output:
0
1
2
3
4
5
*/
while
while 語句執行一個語句或語句塊,直到指定的表達式計算為 false。
class WhileTest { static void Main() { int n = 1; while (n < 5) { Console.WriteLine(n); n++; } } } /*
Output:
1
2
3
4
*/
新聞熱點
疑難解答