开发者

Is it possible to declare a dynamic constant in VB .NET?

I'm trying to save a timestamp into a constant at the beginning of a program's execution to be used throughout the program. Fo开发者_运维百科r example:

Const TIME_STAMP = Format(Now(), "hhmm")

However, this code generates a compiler error - "Constant expression is required." Does that mean all constants in VB .NET have to contain flat, static, hard-coded data? I know that it's possible to initialize a constant with a dynamic value in other languages (such as Java) - what makes it a constant is that after the initial assignment you can no longer change it. Is there an equivalent in VB .NET?


You need to make it Shared Readonly instead of Const - the latter only applies to compile-time constants. Shared Readonly will still prevent anyone from changing the value.

Java doesn't actually have a concept like Const - it just spots when static final values are actually compile-time constants.


What you are looking for is the readonly keyword. A time stamp has to be calculated at run time and cannot be constant.

ReadOnly TIME_STAMP As String = Format(Now(), "hhmm")


By definition, constants are not dynamic. If you want a variable to be set once, and not modified again, I believe you are looking for the ReadOnly keyword...

Public Shared ReadOnly TIME_STAMP = Format(Now(), "hhmm")

Note that 'Shared' is optional.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜