gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:10:38 43 4
gpt4 key购买 nike

在我的类(class)中,我有一个字符串对象的静态字典,其中包含大量项目(它从文件中读取并初始化它们)我写了一个静态构造函数来这样做,这需要几秒钟,但我想做一次是为了更快,因为我是在 ASP.Net 中做的,我希望我的网站没有这种开销我应该怎么做?如果这个构造函数为每个对象运行,那么我正在考虑一些方法,但我想我必须在用户运行的网站的每个页面上运行这个方法,所以我再次认为它是一样的,对吗?您只初始化一大组变量的解决方案是什么?谢谢

最佳答案

根据AppDomain,它针对该类型运行一次.不是每个实例一次。来自 C# 4 规范,第 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.

请注意关于每个封闭类的部分。所以如果你有一个通用类型 Foo<T> , 然后 Foo<string>Foo<object> 的独立类型(等),将有单独的静态字段,并将单独调用其静态构造函数。

关于c# - 在 C# 中,静态构造函数是为对象的每个初始化运行还是只运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7059018/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com