为什么这种打开类型的案例被认为是令人困惑的? [英] Why is this switch on type case considered confusing?

查看:11
本文介绍了为什么这种打开类型的案例被认为是令人困惑的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方法来重构和简化一个函数,我必须根据输入类类型进行数据排序,结果卡在 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 DC.它必须返回一个 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).

这篇关于为什么这种打开类型的案例被认为是令人困惑的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆