Why is this switch on type case considered confusing?(为什么这种打开类型的案例被认为是令人困惑的?)
问题描述
我一直在寻找一种方法来重构和简化一个函数,我必须根据输入类类型进行数据排序,结果卡在 switch(input.GetType()):
I was looking for a way to refactor and simplify one function where I have to do data sorting depending on input class type, and got stuck at switch(input.GetType()):
快速搜索让我找到 为什么 C# 不切换声明允许使用 typeof/GetType()? 与 http://blogs.msdn.com/peterhal/archive/2005/07/05/435760.aspx
Quick search led me to Why doesn't C# switch statement allow using typeof/GetType()? with a link to http://blogs.msdn.com/peterhal/archive/2005/07/05/435760.aspx
我阅读了文档,但没有理由认为情况令人困惑.
I read the documentation, but I don't get the justification that the situation is confusing.
来自文章:
不幸的是,像许多简单"语言功能,类型切换不就像它第一次出现一样简单.这当您查看更多内容时,麻烦就开始了重要的,同样重要的,像这样的例子:
Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:
class C {}
interface I {}
class D : C, I {}
switch typeof(e) {
case C: ... break;
case I: ... break;
default: ... break;
}
这有什么不简单的?调用 typeof(e)
无法返回 - 这是一个 I
D
和 C
.它必须返回一个 Type
而不是接口和类类型的数组 - Type[]
.所以class D
的类型是D
.而 D
对应一个 default:
分支.
What's not simple about it? The call typeof(e)
cannot return - this is a I
D
and C
. It has to return a Type
not an array of interface and class types - Type[]
. So the type of the class D
is D
. And D
corresponds to a default:
branch.
我错过了什么吗?
推荐答案
看来你不希望开关匹配子类.但这会破坏 Liskov 替换原则.(如果你传入一个 C 对象,代码可以工作,但不能使用 D,即使 D 是 C 的子类).
It seems you don't expect the switch to match on subclasses. But this would break the Liskov Substitution Principle. (where if you passed in a C object, the code would work, but not with a D, even though D is a subclass of C).
这篇关于为什么这种打开类型的案例被认为是令人困惑的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这种打开类型的案例被认为是令人困惑的?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01