为什么在这类案件该开关考虑混乱? [英] Why is this switch on type case considered confusing?

查看:147
本文介绍了为什么在这类案件该开关考虑混乱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方式来重构和简化一个功能,我必须做的数据,取决于输入类类型排序,并卡住了在开关(input.GetType()):

快速搜索导致我<一个href=\"http://stackoverflow.com/questions/1711005/why-doesnt-c-switch-statement-allow-using-typeof-gettype\">Why没有C#switch语句允许使用的typeof /的GetType()?一个链接到的 http://blogs.msdn.com/peterhal/archive/2005/07/05/435760.aspx

我阅读文档,但这种情况是令人困惑我不明白的理由。

从文章:


  

不幸的是,就像很多'简单'
  语言特性,类型开关不
  简单,只要它第一次出现。该
  当你看一个更麻烦开始
  显著,并没有那么重要,
  例如像这样的:


  C类{}
接口I {}
D类:C,I {}开关的typeof(五){
案例C:...突破;
案例一:...分手;
默认:...突破;
}

什么是不简单呢?呼叫 typeof运算(E)不能返回 - 这是一个 I D C 。它返回一个键入没有接口和类类型的数组 - 键入[] 。因此, D类的类型是 D 。和 D 相当于默认值:分支

这是我失去了一些东西?


解决方案

看来你不希望切换到匹配的子类。但是,这会破坏里氏替换原则。 (在这里,如果你在一个C对象过去了,code会的工作,但不能用D,即使D是C的子)。

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()):

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.

From the article:

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;
}

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.

An I missing something?

解决方案

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天全站免登陆