为什么这种开关类型的情况被认为是令人困惑的?
我正在寻找一种重构和简化一个函数的方法,我必须根据输入类类型进行数据排序,并陷入 switch(input.GetType()):
快速搜索引导我为什么 C# switch 语句不允许使用typeof/GetType()? 并链接到 http://blogs.msdn.com/peterhal/archive/2005/07/05/435760.aspx
我阅读了文档,但是我不要以情况令人困惑为理由。
来自文章:
不幸的是,就像许多“简单”的事情一样 语言特性,类型切换不是 就像它第一次出现一样简单。这 当你看的更多时,麻烦就开始了 重要且同样重要, 像这样的例子:
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[]
。所以类D
的类型是D
。而D
对应于default:
分支。
我错过了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您不希望开关在子类上匹配。但这会打破里氏替换原则。 (如果您传入一个 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).
我认为 Peter Hallam 的博客文章中的一个完全有效的论点是,如果您重新排序,您不会期望
switch
语句有所不同,因此只有当只有一个分支同时有效时,它才真正有用。 ,而对于Type
来说,一个类在继承链上始终是多种不同的类型。没有人会阻止您使用 if...else 链来执行此操作,您确实希望按照您放置事物的顺序对其进行评估。
I think it's a perfectly valid argument on Peter Hallam's blog post that you don't expect
switch
statement to differ if you reorder things, so it's really only useful if only one branch can be valid at the same time, whereas withType
one class is always multiple different types along the inheritance chain.No one stops you from doing this with an if...else chain, where you do expect it to be evaluated in the order you put things.