Public const string?

前端 未结 4 1340
爱一瞬间的悲伤
爱一瞬间的悲伤 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.

    0 讨论(0)
  • 2021-02-05 05:30

    I think this is one of the best things you can do. Some more suggestions: with strings it's perfectly fine to use consts. In case you'd want to use different types, use static readonly and then initialize in a static constructor.

    For a different approach using enums, see this thread. Since what you're trying to do looks a lot like a string enum, that might be the way to go for you.

    And don't forget that as long as you specify your pages in code, making changes (e.g. renaming or moving a page) will be a pain. Consider using something like resources or sitemaps. (In case you only use the class for a page list, I'd go with using C#'s strongly typed resources - they will behave in the same way as your class and you won't have to code them by hand.)

    0 讨论(0)
  • 2021-02-05 05:34

    A general guideline when using const for defining constant values. Whether these constants are to be accessed outside assembly? If not then declare it as

    internal static class Pages
    {
        public const string Home = "Home.xaml";
        public const string View2 = "View2.xaml";
        /* a few more... */
    }
    
    0 讨论(0)
  • 2021-02-05 05:35

    From the design perspective of your question, it seems like it could get messy fast using a single static object to contain all page references. Can you not just store it in the actual page object?

    class view2 {
        public const string PageName = "View2.xaml";
    
        ... other stuff ...
    }
    

    then call it along the lines of...

    goTo(view2.PageName);
    
    0 讨论(0)
提交回复
热议问题