为什么 C# 没有用“const”来设计?对于变量和方法?
可能的重复:
C# 中的“常量正确性”
我怀疑 const
被简化为通用语言简单性的 C# 规范。我们无法像 C++ 那样将变量引用或方法声明为 const ,是否有特定原因?例如:
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++;
}
}
Possible Duplicate:
“const correctness” in C#
I suspect const
was simplified for the C# spec for general language simplicity. Was there a specific reason we can't declare variable references or methods as const
like we can with C++? e.g.:
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++;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
const 在使用任何地方都会执行值的编译时替换,因此没有任何运行时含义。一般来说,编译器很难确定您对 const 对象的建议(方法是否会修改对象)。您使用 const 关键字作为访问修饰符的建议也会给编写者带来负担,并且您仍然面临验证某些内容是否修改对象的问题。此外,您还向对象强加了一些在所有情况下都没有意义的东西。如果该方法是 const 但您没有将其用作 const 对象,这意味着什么?您想要的功能通常是通过实现接口并仅公开类的“只读”部分来完成的。
A const performs a compile time substitution of the value wherever it is used and therefore doesn't have any runtime meaning. In general what you propose for const objects would be very difficult for the compiler to determine (if a method will modify the object or not). Your proposal to use a const keyword as an access modifier also then puts burden on the writer and you are still left with a problem of verifying of something does or does not modify the object. Also you are imposing something on the object that does not have a meaning in all contexts. What does it mean if the method is const but you aren't using it as a const object? The functionality you want is usually accomplished by implementing an interface and only exposing the "read-only" parts of the class.
我怀疑你问题的第一句话已经回答了这个问题。
I suspect the first sentence of your question answers it.
我相信您可以在 C# 中将变量声明为 const。如果您觉得有必要,也可以使用
static
。http://msdn.microsoft.com/en-us /library/e6w8fe1b(VS.71).aspx
I believe you can declare variables as
const
in C#.static
as well, if you feel the need.http://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.71).aspx