开发者

Why wasn't C# designed with 'const' for variables and methods? [duplicate]

开发者 https://www.devze.com 2023-01-02 09:02 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: “const correctness” in C#
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

“const correctness” in C#

I suspect const was simplified for the C# spec for general language simplicity. Was there a specific r开发者_运维知识库eason 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++;
   }
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消