开发者

Public const string?

开发者 https://www.devze.com 2023-04-12 22:19 出处:网络
Is it ok to use a class like this (design / guideline specific)? I\'m using MVVM Pattern. public static class Pages

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";
    public const str开发者_JS百科ing View2 = "View2.xaml";
    /* a few more... */
}


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.


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... */
}


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);


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

精彩评论

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

关注公众号