开发者

lifetime of a static readonly variable in a class

开发者 https://www.devze.com 2023-02-02 19:29 出处:网络
I have a aspx usercontrol with static readonly string foo = GetFromDB(); now I am wondering what the lifetime of foo is. When does foo get it\'s value. Everytime the usercontrol instance is created

I have a aspx usercontrol with

static readonly string foo = GetFromDB();

now I am wondering what the lifetime of foo is. When does foo get it's value. Everytime the usercontrol instance is created or only once? The reason for wanting to know is that GetFromDB might retur开发者_如何学Pythonn a different value over time. If foo has the same value for a while thats fine. If it never changes untill the app domain is recreated then that isn't.


When does foo get it's value

When you first access the containing class and guaranteed to be executed only once and it will remain the same for the entire life of the AppDomain. You may check the following article on MSDN about static field initialization:

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.


It will only be initialized once when you access the type.

0

精彩评论

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