位置:首頁 > 軟件操作教程 > 編程開發(fā) > C# > 問題詳情

C# 使用switch case表達(dá)式進(jìn)行模式匹配

提問人:劉團(tuán)圓發(fā)布時(shí)間:2020-12-04

switch case基于特定變量的值。<testVar>的類型已知,例如,可以是integer、string或者boolean。如果是integer類型,則變量中存儲的是數(shù)字值,case語句將檢查特定的整數(shù)值(1、2、3等),當(dāng)找到相匹配的數(shù)字后,就執(zhí)行對應(yīng)的代碼。

switch (<testVar>)

{

    case <comparisonVall>:

        <code to execute if <testVar> == <comparisonVall> > 

        break;

    case <comparisonVal2>:

        <code to execute if <testVar> == <comparisonVal2> > 

        break;

    ...

    case <comparisonValN>:

        <code to execute if <testVar> == <comparisonValN> > 

        break; 

    default:

        <code to execute if <testVar> != comparisonVals> 

        break;

}

C# 7中可以基于變量的類型(如string或integer數(shù)組)在switch case中進(jìn)行模式匹配。因?yàn)樽兞康念愋褪羌褐?,所以可以訪問該類型提供的方法和屬性。查看下面的switch結(jié)構(gòu):

switch (<testVar>)

{

    case int value:

        <code to execute if <testVar> is an int > 

    break;

    case string s when s.Length == 0:

        <code to execute if <testVar> is a string with a length = 0 > 

        break;

    ...

    case null:

        <code to execute if <testVar> == null > 

        break; 

    default:

        <code to execute if <testVar> != comparisonVals> 

        break;

}

case關(guān)鍵字之后緊跟的是想要檢查的變量類型(string、int等)。在case語句匹配時(shí),該類型的值將保存到聲明的變量中。例如,若<testVar>是一個(gè)integer類型的值,則該integer的值將存儲在變量value中。when關(guān)鍵字修飾符允許擴(kuò)展或添加一些額外的條件,以執(zhí)行case語句中的代碼。

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部