简体   繁体   English

C# 模式匹配比多态更好吗?

[英]Is C# pattern matching bettern than polymorphism?

C# 7 introduced pattern matching which allows, for example, to switch on types and act according to the underlying type. C# 7 引入了模式匹配,例如,它允许切换类型并根据底层类型进行操作。

Now, and based on the fact that C# is object-oriented the types that we switch on can, for example, implement a same base class or interface and override this base behaviour to achieve what pattern matching can do for us.现在,基于 C# 是面向对象的事实,我们打开的类型可以,例如,实现相同的基类或接口并覆盖此基行为以实现模式匹配可以为我们做的事情。

Why would I use pattern matching instead of this?为什么我要使用模式匹配而不是这个?

Pattern matching plays a central role in functional programming just as polymorphism plays a central role in object-oriented programming.模式匹配在函数式编程中扮演着核心角色,就像多态在面向对象编程中扮演着核心角色一样。

Besides that, I would personally use pattern matching whenever I know the full spectrum of possible types beforehand.除此之外,只要我事先知道所有可能的类型,我就会亲自使用模式匹配。 Eg, a Maybe class which can either be a SomeValue or NoValue.例如,Maybe 类可以是 SomeValue 或 NoValue。 For dynamic scenarios you can't use pattern matching in the first place.对于动态场景,您首先不能使用模式匹配。

To answer the original question: no, pattern matching is not better than polymorphism, it's something different.回答最初的问题:不,模式匹配并不比多态好,它是不同的东西。

Here is another great answer on the topic: https://softwareengineering.stackexchange.com/a/231095这是关于该主题的另一个很好的答案: https : //softwareengineering.stackexchange.com/a/231095

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM