静态构造函数有什么用?
请向我解释一下静态构造函数的使用。为什么以及何时创建静态构造函数?是否可以重载静态构造函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不,你不能超载;静态构造函数对于初始化与类型(或任何其他每类型操作)关联的任何静态字段非常有用 - 特别是对于将所需的配置数据读取到只读字段等有用。
它在第一次运行时由运行时自动运行需要(确切的规则很复杂(参见“beforefieldinit”),并且在 CLR2 和 CLR4 之间发生了微妙的变化)。除非您滥用反射,否则保证最多运行一次(即使两个线程同时到达)。
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.
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).
来自 静态构造函数(C# 编程指南):
From Static Constructors (C# Programming Guide):
当您的静态字段相互依赖且初始化顺序很重要时,静态构造函数也非常有用。如果您通过更改字段顺序的格式化程序/美化器运行代码,那么您可能会发现自己出现了意想不到的空值。
示例:假设我们有这个类:
当您访问
fullUr
时,它将是“http://www.fullUr”。 example.com/foo/bar”。几个月后,您正在清理代码并按字母顺序排列字段(假设它们是更大列表的一部分,因此您不会注意到问题)。您:
您的
fullUrl
值现在只是“http://www.example.com/”,因为设置fullUrl
时,urlFragment
尚未初始化。不好。因此,您添加一个静态构造函数来处理初始化:现在,无论字段的顺序如何,初始化始终都是正确的。
Static constructors are also very useful when you have static fields that rely upon each other such that the order of initialization is important. If you run your code through a formatter/beautifier that changes the order of the fields then you may find yourself with null values where you didn't expect them.
Example: Suppose we had this class:
When you access
fullUr
, it will be "http://www.example.com/foo/bar".Months later you're cleaning up your code and alphabetize the fields (let's say they're part of a much larger list, so you don't notice the problem). You have:
Your
fullUrl
value is now just "http://www.example.com/" sinceurlFragment
hadn't been initialized at the timefullUrl
was being set. Not good. So, you add a static constructor to take care of the initialization:Now, no matter what order you have the fields, the initialization will always be correct.
1.它只能访问类的静态成员。
原因:非静态成员特定于对象实例。如果允许静态构造函数作用于非静态成员,它将反映所有对象实例的更改,这是不切实际的。
2.静态构造函数中不应有参数。
原因:由于它将被CLR调用,所以没有人可以向它传递参数。
3. 只允许有一个静态构造函数。
原因:重载需要两个方法在方法/构造函数定义方面有所不同,这在静态构造函数中是不可能的。
4.它不应该有访问修饰符。
原因:同样的原因是对静态构造函数的相同调用是由 CLR 而不是由对象进行的,不需要对其具有访问修饰符
1.It can only access the static member(s) of the class.
Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical.
2.There should be no parameter(s) in static constructor.
Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it.
3.Only one static constructor is allowed.
Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor.
4.There should be no access modifier to it.
Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it
您可以使用静态构造函数来初始化静态字段。它在使用这些字段之前的不确定时间运行。 Microsoft 的文档和许多开发人员警告说,类型上的静态构造函数会产生大量开销。
为了获得最大性能,最好避免使用静态构造函数。
更新:您不能在同一类中使用多个静态构造函数,但是您可以将其他实例构造函数与(最多)一个静态构造函数一起使用。
you can use static constructor to initializes static fields. It runs at an indeterminate time before those fields are used. Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead.
It is best to avoid static constructors for maximum performance.
update: you can't use more than one static constructor in the same class, however you can use other instance constructors with (maximum) one static constructor.
使用静态构造函数的一个具体原因是创建一个“超级枚举”类。这是一个(简单的、人为的)示例:
您使用它的方式与任何其他枚举非常相似(在语法外观上):
与常规
enum
相比,它的优点是您可以轻松封装相关信息。一个缺点是您不能在switch
语句中使用这些值(因为它需要常量值)。One specific reason to use a static constructor is to create a 'super enum' class. Here's a (simple, contrived) example:
You'd use it very similarly (in syntactical appearance) to any other enum:
The advantage of this over a regular
enum
is that you can encapsulate related info easily. One disadvantage is that you can't use these values in aswitch
statement (because it requires constant values).来自微软文档
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors" microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
静态构造函数(C# 编程指南)
静态构造函数用于初始化任何静态数据,或执行只需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前会自动调用它。
备注
静态构造函数具有以下属性:
static readonly
的字段只能作为其声明的一部分或在静态构造函数中进行分配。当不需要显式静态构造函数时,请在声明时初始化静态字段,而不是通过静态构造函数来初始化,以获得更好的运行时优化。用法
LoadLibrary
方法时,静态构造函数在为非托管代码创建包装类时也很有用。From Microsoft documentation
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
Static Constructors (C# Programming Guide)
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.
Remarks
Static constructors have the following properties:
static readonly
may only be assigned as part of its declaration or in a static constructor. When an explicit static constructor isn't required, initialize static fields at declaration rather than through a static constructor for better runtime optimization.Parallel.Invoke
and Parallel LINQ queries.Usage
LoadLibrary
method.静态构造函数
仅调用所创建类的第一个实例。并用于执行在类的生命周期中只需要执行一次的特定操作。Static constructor
called only the first instance of the class created. and used to perform a particular action that needs to be performed only once in the life cycle of the class.