为什么const从Java和C#中删除?

为什么const从Java和C#中删除?

问题描述:

我知道这已经讨论了很多次,但我不确定我是否真的理解为什么 Java和C#设计者选择从这些语言中省略此功能。我对如何使用解决方案(使用接口,克隆或任何其他替代方法)感兴趣,而是对决策背后的理由。

I know this has been discussed many times, but I am not sure I really understand why Java and C# designers chose to omit this feature from these languages. I am not interested in how I can make workarounds (using interfaces, cloning, or any other alternative), but rather in the rationale behind the decision.

一个语言设计的透视,为什么这个功能被拒绝?

PS:我使用的单词,如忽略 ,因为C#是以加法(而不是减法)方法设计的。但是,我使用这样的单词,因为在这些语言被设计之前,C ++中存在的特征,所以在从程序员工具箱中删除的意义上被忽略。

P.S: I'm using words such as "omitted", which some people may find inadequate, as C# was designed in an additive (rather than subtractive) approach. However, I am using such words because the feature existed in C++ before these languages were designed, so it is omitted in the sense of being removed from a programmer's toolbox.

采访中,Anders说:

In this interview, Anders said:


Anders Hejlsberg:是的。关于
const,很有趣,因为我们
总是听到这个投诉:
你为什么不用const?隐含
在问题是,为什么不
有const由
运行时强制执行?这真的是人们
要求,虽然他们不来
出来说这样说。

Anders Hejlsberg: Yes. With respect to const, it's interesting, because we hear that complaint all the time too: "Why don't you have const?" Implicit in the question is, "Why don't you have const that is enforced by the runtime?" That's really what people are asking, although they don't come out and say it that way.

在C ++中const工作的原因是
,因为你可以把它丢弃。如果你
不能把它丢弃,那么你的世界
会吸。如果你声明一个方法
需要一个const Bla,你可以通过
它是一个非const Bla。但如果是
其他方式你不能。如果你
声明一个接受
非const Bla的方法,你不能传递它
const Bla。所以现在你被卡住了。所以你
逐渐需要一个const版本的
一切不const,你
结束了一个影子世界。在C ++中,
可以使用它,因为和
一样,C ++中的任何东西都是纯可选的
是否需要这个检查。
如果你不喜欢它,你可以打破常规的

The reason that const works in C++ is because you can cast it away. If you couldn't cast it away, then your world would suck. If you declare a method that takes a const Bla, you could pass it a non-const Bla. But if it's the other way around you can't. If you declare a method that takes a non-const Bla, you can't pass it a const Bla. So now you're stuck. So you gradually need a const version of everything that isn't const, and you end up with a shadow world. In C++ you get away with it, because as with anything in C++ it is purely optional whether you want this check or not. You can just whack the constness away if you don't like it.