公共常量字符串? [英] Public const string?

查看:64
本文介绍了公共常量字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用这样的类(特定于设计/指南)吗?我正在使用 MVVM 模式.

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 string View2 = "View2.xaml";
    /* a few more... */
}

推荐答案

constpublic static readonly 之间存在显着差异,您应该考虑使用哪个护理:

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

  • 如果您更改了值但不重新编译客户端,如果您使用 const,它们仍将使用原始值.使用 public static readonly,他们将看到更新后的值.如果您无论如何都重新编译所有客户端,这不是问题.
  • 只有 const 形式是编译时常量,这意味着它可以用于:
    • 属性参数
    • 切换语句
    • 可选参数声明
    • 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

      如果您愿意在更改值时重新编译所有客户端,那么第二个要点的好处指向使用 const.

      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.

      当然,我想知道 Pages 真的 是否需要公开......这听起来可能是 internal 的东西,与internal 成员 - 在这一点上 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.

      这篇关于公共常量字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆