在 C# 中,静态构造函数是为对象的每次初始化运行,还是只运行一次?

发布于 2024-11-29 16:05:08 字数 226 浏览 0 评论 0原文

在我的类中,我有一个字符串对象的静态字典,其中包含大量项目(它从文件中读取并初始化它们)我编写了一个静态构造函数来执行此操作,这需要几秒钟,但我想执行一次为了更快,因为我是在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪荡不羁 2024-12-06 16:05:08

它针对每个 AppDomain 的类型运行一次。每个实例不是一次。来自 C# 4 规范,第 10.12 节:

封闭类类型的静态构造函数在给定的应用程序域中最多执行一次。静态构造函数的执行由应用程序域中发生的以下第一个事件触发:

  • 创建了该类类型的实例。
  • 引用类类型的任何静态成员。

请注意关于每个封闭类的部分。因此,如果您有一个泛型类型 Foo,那么 FooFoo的单独类型(等等) ,将具有单独的静态字段,并将单独调用其静态构造函数。

It runs once for the type, per AppDomain. Not once per instance. From the C# 4 spec, section 10.12:

The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  • An instance of the class type is created.
  • Any of the static members of the class type are referenced.

Note the part about it being per closed class. So if you have a generic type Foo<T>, then Foo<string> is a separate type to Foo<object> (etc), will have separate static fields, and will have its static constructor invoked separately.

行雁书 2024-12-06 16:05:08

它在应用程序的生命周期内仅运行一次。

来自 MSDN - 静态构造函数

静态构造函数用于初始化任何静态数据,或执行只需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前会自动调用它。

It runs one time only during the lifetime of the application.

From MSDN - Static Constructors:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文