简体   繁体   English

.NET中的常量与String.Format

[英]Constants in .NET with String.Format

I have two constants: 我有两个常数:

public const string DateFormatNormal = "MMM dd";
public const string TimeFormatNormal = "yyyy H:mm";

after i decided to have another constant base on those two: 在我决定在这两个方面有另一个基础之后:

public const string DateTimeFormatNormal = String.Format("{0} {1}", DateFormatNormal, TimeFormatNormal);

But i get compile error The expression being assigned to 'Constants.DateTimeFormatNormal' must be constant 但我得到编译错误The expression being assigned to 'Constants.DateTimeFormatNormal' must be constant

After i try do do like that: 我尝试后做那样的事情:

public const string DateTimeFormatNormal = DateFormatNormal + " " + TimeFormatNormal;

It is working with + " " + but i still prefer to use something similar to String.Format("{0} {1}", ....) any thoughts how i can make it work? 它正在使用+ " " +但我仍然喜欢使用类似于String.Format("{0} {1}", ....)任何想法,我怎么能使它工作?

Unfortunately not. 不幸的是。 When using the const keyword, the value needs to be a compile time constant. 使用const关键字时,该值必须是编译时常量。 The reslult of String.Format isn't a compile time constant so it will never work. String.Format的结果不是编译时常量,所以它永远不会工作。

You could change from const to readonly though and set the value in the constructor. 您可以从const更改为readonly并在构造函数中设置值。 Not exact the same thing...but a similar effect. 不完全相同的东西......但效果类似。

I find myself in this situation often and I end up converting it to something that looks like: 我经常发现自己处于这种情况,最后我把它转换成看起来像这样的东西:

public static readonly string DateTimeFormatNormal = String.Format("{0} {1}", DateFormatNormal, TimeFormatNormal);

(Hope that's right, I'm a VB.NET dev, same idea) (希望是对的,我是一个VB.NET开发者,同样的想法)

Public Shared ReadOnly DateTimeFormatNormal As String = String.Format("{0} {1}", DateFormatNormal, TimeFormatNormal)

Public Shared ReadOnly is pretty darn close to Public Const . Public Shared ReadOnly非常接近Public Const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM