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

Patterns

The other big addition is you can now match patterns in C# 7 using the is keyword. This simplifies testing for null and matching against types, among other things. It also lets you easily use the cast value. This is a simpler alternative to using full polymorphism (where a derived class can be treated as a base class and override methods). However, if you control the code base and are able to make use of polymorphism properly, then you should still do this and follow good object-oriented programming (OOP) principles.

In the following example, pattern matching is used to parse the type and value of an unknown object:

private static int PatternMatch(object obj)
{
if (obj is null)
{
return 0;
}
if (obj is int i)
{
return i++;
}
if (obj is DateTime d ||
(obj is string str && DateTime.TryParse(str, out d)))
{
return d.DayOfYear;
}
return -1;
}

You can also use pattern matching in the case of a switch statement, and you can switch on non-primitive types, such as custom objects.

主站蜘蛛池模板: 库尔勒市| 黑山县| 蓬安县| 凤阳县| 旌德县| 昌吉市| 阳江市| 镶黄旗| 阳城县| 名山县| 衢州市| 潼关县| 柘荣县| 雷山县| 苏尼特右旗| 交口县| 菏泽市| 揭西县| 渑池县| 沅江市| 文山县| 精河县| 南和县| 宁波市| 丹巴县| 武胜县| 阿拉尔市| 高雄县| 临泽县| 普兰县| 嵩明县| 旺苍县| 博兴县| 水城县| 延津县| 义马市| 乌拉特后旗| 东丽区| 古蔺县| 临泉县| 连山|