可能重复:
C#中的"const correctness"
我怀疑constC#规范简化了一般语言的简单性.是否有一个特定的原因我们不能const像C++那样声明变量引用或方法?例如:
const MyObject o = new MyObject(); // Want const cast referenece of MyObject
o.SomeMethod(); // Theoretically legal because SomeMethod is const
o.ChangeStuff(); // Theoretically illegal because ChangeStuff is not const
class MyObject
{
public int val = 0;
public void SomeMethod() const
{
// Do stuff, but can't mutate due to const declaration.
}
public void ChangeStuff()
{
// Code mutates this instance. Can't call with const reference.
val++;
}
}
Run Code Online (Sandbox Code Playgroud)