- ASP.NET Core 2 High Performance(Second Edition)
- James Singleton
- 177字
- 2021-07-08 09:38:59
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.
- 造個小程序:與微信一起干件正經事兒
- Effective C#:改善C#代碼的50個有效方法(原書第3版)
- Mastering Ember.js
- Network Automation Cookbook
- 羅克韋爾ControlLogix系統應用技術
- 數據結構(Python語言描述)(第2版)
- PHP+MySQL網站開發項目式教程
- Flutter跨平臺開發入門與實戰
- Haskell Data Analysis Cookbook
- C語言程序設計上機指導與習題解答(第2版)
- HTML 5與CSS 3權威指南(第3版·上冊)
- 打開Go語言之門:入門、實戰與進階
- 區塊鏈國產化實踐指南:基于Fabric 2.0
- Mastering Adobe Captivate 7
- SQL Server 2008中文版項目教程(第3版)