为什么C#不提供const类似于C ++? [英] Why doesn't C# offer constness akin to C++?
问题描述
C#中的引用与C ++中的引用非常相似,只是它们是垃圾回收的。
为什么C#编译器很难支持以下操作:
- 成员函数标记为
const
。 - 引用数据类型(字符串除外)
const
,可以调用
const
成员函数?
我相信如果C#支持这将是非常有用的。一个,它真的会帮助看起来广泛的同性恋放弃哪些C#程序员返回对私人数据的裸露引用(至少这是我在我的工作场所看到的)。
还是已经有一些等价的C#,我错过了? (我知道 readonly
和 const
关键字,但它们不能真正满足上述目的)
我怀疑有一些实际原因,有一些理论原因:
- 常数应用于对象或参考吗?如果它在引用,这应该是编译时只,还是在参考本身的一点?
- 你能不能像在C ++中那样把它丢弃?这听起来不像你想在托管平台上的东西...但是在C ++中所有那些有意义的时候呢?
- 语法变得棘手(IMO)当你有一个以上的类型涉及到一个声明 - 想到数组,泛型等。它可能变得很难确定哪个位是const。
- 如果你不能抛弃它,每个人都必须正确。换句话说,.NET框架类型和任何其他第三方库使用都必须做正确的事情,或者你留下的错误的情况下,你的代码不能做正确的事情,因为一个微妙的问题, const。
有一个很大的原因,为什么现在不能支持 / p> 我同意有一些常数指示器,但我看不到它发生,恐怕。 编辑:有一个关于Java社区中这种肆虐的争论,有关相关错误您可能会感兴趣。 References in C# are quite similar to those on C++, except that they are garbage collected. Why is it then so difficult for the C# compiler to support the following: I believe it would be really useful if C# supported this. For one, it'll really help the seemingly widespread gay abandon with which C# programmers return naked references to private data (at least that's what I've seen at my workplace). Or is there already something equivalent in C# which I'm missing? (I know about the I suspect there are some practical reasons, and some theoretical reasons: There's a big one in terms of why it can't be supported now though: I agree it would be useful to have some sort of constness indicator, but I can't see it happening, I'm afraid. EDIT: There's been an argument about this raging in the Java community for ages. There's rather a lot of commentary on the relevant bug which you may find interesting. 这篇关于为什么C#不提供const类似于C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
const
.const
, through which only const
member functions can be called ?readonly
and const
keywords, but they don't really serve the above purpose)