- 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.
- Docker and Kubernetes for Java Developers
- Kali Linux Web Penetration Testing Cookbook
- Visual Studio 2012 Cookbook
- WebAssembly實戰
- 垃圾回收的算法與實現
- Debian 7:System Administration Best Practices
- Interactive Data Visualization with Python
- Learning Elixir
- 三維圖形化C++趣味編程
- Python Deep Learning
- INSTANT Sencha Touch
- SAS數據統計分析與編程實踐
- Mastering Rust
- Python編程實戰
- Python Data Analysis Cookbook