我一直在寻找一种方法来重构和简化一个函数,在该函数中我必须根据输入类类型进行数据排序,但卡在了 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
D
和 C
。它必须返回 Type
而不是接口(interface)和类类型的数组 - Type[]
。所以class D
的类型是D
。而D
对应一个default:
分支。
我错过了什么吗?
最佳答案
您似乎不希望开关在子类上匹配。但这会破坏里氏替换原则。 (如果你传入一个 C 对象,代码可以工作,但不能使用 D,即使 D 是 C 的子类)。
关于c# - 为什么这个 switch on 类型的案例被认为是令人困惑的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6304815/