在C#中没有静态构造函数运行对象的每个初始化,还是只有一次? [英] in C# does Static constructor run for each initialization of object, or only once?

查看:587
本文介绍了在C#中没有静态构造函数运行对象的每个初始化,还是只有一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的课我有一个字符串的静态Dictionary对象,其中包含项目的大数目(它从文件中读取和初始它们)我写了一个静态构造函数这样做,它需要几秒钟,但我想做一次要快,因为我在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

推荐答案

据该类型运行一次,每的AppDomain 。每个实例一次都没有。从C#4规格的,第10.12节:

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:


      
  • 类类型的实例被创建。

  •   
  • 任何类类型的静态成员被引用。

  •   

请注意关于它的每关闭的类是部分。所以,如果你有一个泛型类型美孚< T> ,那么美孚<串> 是一个独立的类型美孚<对象> (ETC),将有单独的静态字段,都会有其静态构造函数调用单独

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.

这篇关于在C#中没有静态构造函数运行对象的每个初始化,还是只有一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆