什么是使用静态构造函数? [英] What is the use of static constructors?

查看:172
本文介绍了什么是使用静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请给我解释一下使用静态构造函数。为什么我们何时将创建一个静态构造函数,并有可能超载呢?

Please explain to me the use of static constructor. Why and when would we create a static constructor and is it possible to overload one?

推荐答案

没有你不能超负荷;静态构造为初始化用型(或其他任何次式操作)相关联的任何静态字段有用 - 特别有用,用于读取所需的配置数据到只读字段等

No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.

这是由运行时自动运行第一次需要(确切的规则也有复杂的(参见beforefieldinit),并CLR2和CLR4之间微妙的改变)。除非你滥用反思,这是保证运行的最多的一次(即使两个线程在同一时间到达)。

It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).

这篇关于什么是使用静态构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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