在 C# 中,静态构造函数是为对象的每次初始化运行,还是只运行一次?
在我的类中,我有一个字符串对象的静态字典,其中包含大量项目(它从文件中读取并初始化它们)我编写了一个静态构造函数来执行此操作,这需要几秒钟,但我想执行一次为了更快,因为我是在 ASP.Net 中进行的,并且我希望我的网站没有这种开销,我应该做什么?如果这个构造函数为每个对象运行,那么我正在考虑某种方法,但我想我必须在用户运行的网站的每个页面中运行这个方法,所以我再次认为它会是相同的,对吗? 仅初始化一大组变量一次的解决方案是什么?谢谢
in my Class I have a static dictionary of strings object which contains a big number of Items (it reads from a file and initial them) I wrote a static constructor to do so and it takes a few seconds, but I want to do it once to be faster, since I'm doing it in ASP.Net and I want my website not to have this overhead what should I do? if this constructor runs for each object then I was thinking of some method instead but I guess I have to run this method in each page of website which user runs, so I think again it would be the same, am I right?
what's your solution for initialization a big set of variables only once? thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它针对每个
AppDomain
的类型运行一次。每个实例不是一次。来自 C# 4 规范,第 10.12 节:请注意关于每个封闭类的部分。因此,如果您有一个泛型类型
Foo
,那么Foo
是Foo
It runs once for the type, per
AppDomain
. Not once per instance. From the C# 4 spec, section 10.12:Note the part about it being per closed class. So if you have a generic type
Foo<T>
, thenFoo<string>
is a separate type toFoo<object>
(etc), will have separate static fields, and will have its static constructor invoked separately.它在应用程序的生命周期内仅运行一次。
来自 MSDN - 静态构造函数:
It runs one time only during the lifetime of the application.
From MSDN - Static Constructors: