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

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.

主站蜘蛛池模板: 亳州市| 大田县| 瓮安县| 永年县| 米易县| 佛学| 祥云县| 油尖旺区| 凌海市| 北宁市| 湄潭县| 河西区| 靖远县| 岗巴县| 崇文区| 乌海市| 荆州市| 灌阳县| 西充县| 天长市| 纳雍县| 琼海市| 岳阳市| 侯马市| 平山县| 武乡县| 葫芦岛市| 牡丹江市| 大田县| 廊坊市| 华阴市| 边坝县| 兴化市| 承德市| 唐河县| 建宁县| 鹤壁市| 泾源县| 同江市| 泉州市| 阜宁县|