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

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.

主站蜘蛛池模板: 铜梁县| 阜康市| 鄄城县| 宜宾县| 白玉县| 杭锦后旗| 关岭| 余庆县| 萨嘎县| 三门峡市| 依兰县| 凭祥市| 榆社县| 英山县| 台北县| 荣成市| 邵阳县| 乌拉特前旗| 渝北区| 疏附县| 峡江县| 甘泉县| 梅河口市| 义乌市| 工布江达县| 资溪县| 嵊泗县| 腾冲县| 信丰县| 湖南省| 屏东县| 台中县| 连山| 南部县| 普宁市| 岚皋县| 曲沃县| 米易县| 镇江市| 绥宁县| 朝阳市|