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

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.

主站蜘蛛池模板: 遂溪县| 德格县| 额尔古纳市| 黄浦区| 新竹县| 进贤县| 新巴尔虎右旗| 汉中市| 营口市| 建德市| 鲁山县| 修水县| 克东县| 福州市| 清丰县| 鲁山县| 汉寿县| 美姑县| 自贡市| 彭州市| 江陵县| 会宁县| 兴安盟| 静安区| 礼泉县| 绥江县| 信宜市| 桂阳县| 秦皇岛市| 若羌县| 遂宁市| 河源市| 临猗县| 清新县| 历史| 平舆县| 铅山县| 府谷县| 厦门市| 留坝县| 富蕴县|