zoukankan      html  css  js  c++  java
  • static vs const in c#

    All constants declarations are implicitly static, and the C# specification states that the (redundant) inclusion of the static modifier is prohibited. I believe this is to avoid the confusion which could occur if a reader were to see two constants, one declared static and one not - they could easily assume that the difference in specification implied a difference in semantics. Having said that, there is no prohibition on redundantly specifying an access modifier which is also the default one, where there is a choice. For instance, a (concrete) method can be explicitly marked as private despite that being the default. The rule appears to be that where there is no choice (e.g. a method declaration in an interface) the redundant modifier is prohibited. Where there is a choice, it's allowed.

     

    I think "const" and "static readonly" are not the same. The "const" must be known at compile time. However "static readonly" is initialized at runtime, but its the value cannot be changed (because it's readonly) after initialization.

    In practice, have a look at this example:

    // Trying to assign an instance of a class StorageFolder (which can't be known at compile time) to FOO

    // this will compile

    private static readonly StorageFolder   FOO = KnownFolders.DocumentsLibrary;

    // this won't compile

    private const  StorageFolder            FOO = KnownFolders.DocumentsLibrary;

  • 相关阅读:
    SGU 456 Annuity Payment Scheme
    SPOJ AMR10F Cookies Piles
    poj 2823 Sliding Window (单调队列)
    (bc #45) A
    cf 442C. Artem and Array
    cf 442B Andrey and Problem
    cf 443B Kolya and Tandem Repeat
    (BC 一周年) hdu 5312 Sequence
    (BC 一周年)hdu 5311 Hidden String
    (BC 一周年)hdu 5310 Souvenir
  • 原文地址:https://www.cnblogs.com/jjj250/p/2848819.html
Copyright © 2011-2022 走看看