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

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.

主站蜘蛛池模板: 哈尔滨市| 杭锦后旗| 揭东县| 任丘市| 肥西县| 宁陕县| 晴隆县| 翁牛特旗| 彰化市| 梅河口市| 唐山市| 平阴县| 白朗县| 凤台县| 武邑县| 庆云县| 莱芜市| 宁武县| 清镇市| 景泰县| 新河县| 黄冈市| 英德市| 秦皇岛市| 宣恩县| 商洛市| 同仁县| 太仆寺旗| 大石桥市| 马公市| 镇康县| 马龙县| 景宁| 临海市| 当阳市| 女性| 阿拉善右旗| 芦溪县| 亚东县| 哈密市| 茌平县|