C#探祕系列(二)

深入類之前的準備

在討論C#的類之前,有必要對C#中不同於C++的迷人的新特性作一總結,這對之後的學習大有裨益。

一、Switch語句

使用switch語句有三點需要注意,其中1、3點爲新特性:

1.現在在執行一條case語句後,程序流不能跳至下一case語句中,而在C++中可以。如:

int var = 100;
switch (var) 
{ 
    case 100: Console.WriteLine("<Value is 100>"); // 這裏沒有 break 
    case 200: Console.WriteLine("<Value is 200>"); break; 
}

在C++中的輸出爲

<Value is 100><Value is 200>

而在C#中,你將得到一個編譯錯誤:

error CS0163: Control cannot fall through 
       from one case label ('case 100:') to another

如果你想要從”case 100”跳到”case 200”, 就必須用goto語句顯示地跳轉:

int var = 100;
switch (var) 
{ 
    case 100: Console.WriteLine("<Value is 100>");
    goto case 200;
    case 200: Console.WriteLine("<Value is 200>"); break; 
}

2、但你可以像C++中這樣用:

switch (var) 
{
    case 100: 
    case 200: Console.WriteLine("100 or 200<VALUE is 200>"); break; 
}

3、C#允許字符串匹配case

const string WeekEnd = "Sunday";
const string WeekDay1 = "Monday";

//....

string WeekDay = Console.ReadLine();
switch (WeekDay ) 
{ 
case WeekEnd: Console.WriteLine("It's weekend!!"); break; 
case WeekDay1: Console.WriteLine("It's Monday"); break;

}

二、foreach語句

新版的Java也引入foreach語句,foreach可以避免引起越界的問題,同時簡化代碼,而可讀性又不會降低,可謂一箭三雕:

static void Main( string[] args )
{
foreach (String s in args)
{
Console.WriteLine( "The consloe arguments are: {0}", s );
}
}

預處理命令#region

預處理指令#region可以通過一條註釋標記一段代碼文本。其主要用途是使Visual Studio 這樣的工具可以標記一個代碼區域,在編輯器中將該區域折起來,只顯示區域的註釋。
在用C#編程時,我們經常會用#region將using 語句的代碼區摺疊起來,如:

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

以上基本上是進入類話題中必備的知識點了,當然還有一些較爲生僻的用法,咱們會在後面即用即談。

發佈了29 篇原創文章 · 獲贊 12 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章