官术网_书友最值得收藏!

Pattern matching

Staying with the PopulateStorageSpacesList() method, we can see the use of another C# 7 feature called pattern matching. The spaces is null line of code is probably the simplest form of pattern matching. In reality, pattern matching supports several patterns.

Consider a switch statement:

switch (objObject) 
{ 
    case null: 
        WriteLine("null"); // Constant pattern 
        break; 
 
    case Document doc when doc.Author.Equals("Stephen King"): 
        WriteLine("Stephen King is the author"); 
        break; 
 
    case Document doc when doc.Author.StartsWith("Stephen"): 
        WriteLine("Stephen is the author"); 
        break; 
 
    default: 
        break; 
} 

Pattern matching allows developers to use the is expression to see whether something matches a specific pattern. Bear in mind that the pattern needs to check for the most specific to the most general pattern. If you simply started the case with case Document doc: then all the objects passed to the switch statement of type Document would match. You would never find specific documents where the author is Stephen King or starts with Stephen.

For a construct inherited by C# from the C language, it hasn't changed much since the '70s. C# 7 changes all that with pattern matching.

主站蜘蛛池模板: 吐鲁番市| 运城市| 天全县| 滨州市| 五寨县| 垣曲县| 太仓市| 林周县| 大理市| 米泉市| 无为县| 通道| 安化县| 大化| 阿克苏市| 静安区| 正镶白旗| 望都县| 三都| 开原市| 荆门市| 江都市| 盱眙县| 鲁山县| 准格尔旗| 潞城市| 东乌| 双桥区| 潮安县| 金溪县| 和顺县| 桃江县| 明溪县| 贵港市| 荥经县| 新竹县| 金乡县| 邵阳县| 商南县| 龙南县| 财经|