c# - 为什么这个 switch on 类型的案例被认为是令人困惑的?

标签 c# switch-statement

我一直在寻找一种方法来重构和简化一个函数,在该函数中我必须根据输入类类型进行数据排序,但卡在了 switch(input.GetType()):

快速搜索让我找到了 Why doesn't C# switch statement allow using typeof/GetType()?带有指向 http://blogs.msdn.com/peterhal/archive/2005/07/05/435760.aspx 的链接

我阅读了文档,但没有理由认为情况令人困惑。

来自文章:

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 而不是接口(interface)和类类型的数组 - Type[]。所以class D的类型是D。而D对应一个default:分支。

我错过了什么吗?

最佳答案

您似乎不希望开关在子类上匹配。但这会破坏里氏替换原则。 (如果你传入一个 C 对象,代码可以工作,但不能使用 D,即使 D 是 C 的子类)。

关于c# - 为什么这个 switch on 类型的案例被认为是令人困惑的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6304815/

相关文章:

c# - Visual Studio 2013.2 无法生成,因为 IIS 正在锁定程序集

c# - 如何使用 linq-c# 将 XML 元素值转换为 int

java - 在java中的不同方法中引用条件切换的每种情况

c - 我的 switch 语句有什么问题?

c# - 无法将 int 转换为 bool

c# - 检查非托管 DLL 是 32 位还是 64 位?

c# - python3 pythonnet 泛型代表

c# - 使用默认大小写打开枚举将无法编译。

Javascript - div innerHTML 不会改变

c#: 切换大小写: if (case:)