Public const string?

前端 未结 4 1389
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 04:48

Is it ok to use a class like this (design / guideline specific)? I\'m using MVVM Pattern.

public static class Pages
{
    public const string Home = \"Home.xaml\         


        
4条回答
  •  轮回少年
    2021-02-05 05:30

    There are significant differences between const and public static readonly, and you should consider which to use with care:

    (By "client" here, I mean "code in a different assembly referring to the member.)

    • If you change the value but don't recompile clients, they will still use the original value if you use const. With public static readonly, they will see the updated value. If you recompile all clients anyway, this isn't a problem.
    • Only the const form is a compile time constant, which means it can be used in:
      • Attribute arguments
      • Switch statements
      • Optional parameter declarations

    If you're happy to recompile all your clients if you ever change the value, the benefits of the second bullet point point towards using const.

    Of course, I wonder whether Pages really needs to be public anyway... it sounds like something which could be internal, with internal members - at which point the downsides of const go away entirely.

提交回复
热议问题