开发者

Constants in .NET with String.Format

开发者 https://www.devze.com 2023-03-30 07:15 出处:网络
I have two constants: public const string DateFormatNormal = \"MMM dd\"; public const string TimeFormatNormal = \"yyyy H:mm\";

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);
开发者_StackOverflow中文版

But i get compile error 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?


Unfortunately not. When using the const keyword, the value needs to be a compile time constant. The reslult of String.Format isn't a compile time constant so it will never work.

You could change from const to readonly though and set the value in the constructor. 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)

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

Public Shared ReadOnly is pretty darn close to Public Const.

0

精彩评论

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