- 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.
- Drupal 8 Blueprints
- The Modern C++ Challenge
- Rust編程從入門到實(shí)戰(zhàn)
- C語言程序設(shè)計(jì)
- Scratch 3游戲與人工智能編程完全自學(xué)教程
- Responsive Web Design by Example
- Learning Apache Mahout Classification
- Mathematica Data Analysis
- Android系統(tǒng)級(jí)深入開發(fā)
- 單片機(jī)C語言程序設(shè)計(jì)實(shí)訓(xùn)100例
- 圖數(shù)據(jù)庫實(shí)戰(zhàn)
- Mastering Akka
- 持續(xù)集成與持續(xù)交付實(shí)戰(zhàn):用Jenkins、Travis CI和CircleCI構(gòu)建和發(fā)布大規(guī)模高質(zhì)量軟件
- Web性能實(shí)戰(zhàn)
- Java并發(fā)實(shí)現(xiàn)原理:JDK源碼剖析