之前對于Break和Continue;ReadOnly和Const;ref和out,params之類的基礎東東學習過,但是一直沒有仔細去研究到底是怎么一回事兒,最近在開發中用到了,仔細來做個總結:
1、Break和Continue
break是跳出整個循環體,不再執行本循環,
continue是結束單次循環,繼續下一次循環
1 #region Break測試 2 3 Console.WriteLine("========Break========"); 4 int x = 0; 5 while (x++ < 20) 6 { 7 if (x == 3) 8 { 9 break;10 }11 Console.WriteLine("{0}/n",x);12 } 13 #endregionView Code
1 #region Continue測試 2 Console.WriteLine("========Continue========"); 3 int k = 0; 4 while (k++ < 10) 5 { 6 if (k == 3) 7 { 8 continue; 9 }10 Console.WriteLine("{0}/n",k);11 } 12 #endregionView Code
2、ReadOnly和Const
1. const修飾的常量在聲明的時候必須初始化;readonly修飾的常量則可以延遲到構造函數初始化
2. const修飾的常量在編譯期間就被解析,即常量值被替換成初始化的值(編譯時常量);readonly修飾的常量則延遲到運行的時候(運行時常量)
3. 此外,Const常量既可以聲明在類中也可以在函數體內,但是Static ReadOnly常量只能聲明在類中。
1 #region ReadOnly 2 static readonly int A = B * 10; 3 static readonly int B = 10; 4 5 const int j = k * 10; 6 const int k = 10; 7 8 static void Main(string[] args) 9 {10 Console.WriteLine("===Readonly輸出的值是:===");11 Console.WriteLine("A is {0}.B is {1}", A, B);12 Console.WriteLine("===Const輸出的值是:===");13 Console.WriteLine("j is {0}.k is {1}", j, k);14 Console.ReadKey();15 }16 #endregionView Code
3、ref 和 out,params
問題的引出:
現需要通過一個叫Swap的方法交換a,b兩個變量的值。交換前a=1,b=2,斷言:交換后a=2,b=1
現編碼如下:
1 1class PRogram 2 2 { 3 3 static void Main(string[] args) 4 4 { 5 5 int a = 1; 6 6 int b = 2; 7 7 Console.WriteLine("交換前/ta={0}/tb={1}/t",a,b); 8 8 Swap(a,b); 9 9 Console.WriteLine("交換后/ta={0}/tb={1}/t",a,b);10 10 Console.Read();11 11 }12 12 //交換a,b兩個變量的值13 13 private static void Swap(int a,int b)14 14 {15 15 int temp = a;16 16 a = b;17 17 b = temp;18 18 Console.WriteLine("方法內/ta={0}/tb={1}/t",a,b);19 19 }20 20 }View Code
運行結果:
交換前 a = 1 b = 2
方法內 a = 2 b = 1
交換后 a = 1b = 2
并未達到我們的需求!
原因分析:int類型為值類型,它存在于線程的堆棧中。當調用Swap(a,b)方法時,相當于把a,b的值(即1,2)拷貝一份,然后在方法內交換這兩個值。交換完后,a還是原來的a,b還是原來的b。這就是C#中按值傳遞的原理,傳遞的是變量所對應數據的一個拷貝,而非引用。
修改代碼如下即可實現我們想要的結果:
1 class Program 2 2 { 3 3 static void Main(string[] args) 4 4 { 5 5 int a = 1; 6 6 int b = 2; 7 7 Console.WriteLine("交換前/ta={0}/tb={1}/t",a,b); 8 8 Swap(ref a,ref b); 9 9 Console.WriteLine("交換后/ta={0}/tb={1}/t",a,b);10 10 Console.Read();11 11 }12 12 //交換a,b兩個變量的值13 13 private static void Swap(ref int a, ref int b)14 14 {15 15 int temp = a;16 16 a = b;17 17 b = temp;18 18 Console.WriteLine("方法內/ta={0}/tb={1}/t",a,b);19 19 }20 20 }View Code
新聞熱點
疑難解答