C#编译器是否放置了默认的静态构造函数? [英] Does C# compiler put a default static constructor?
本文介绍了C#编译器是否放置了默认的静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道C#编译器会为实例类型设置一个默认的no-args构造函数,但如果该类是静态的,会发生什么?情况是一样吗?
我尝试过:
查看C#编程指南中的静态构造函数,但没有找到与我的问题相关的任何内容。
I know that the C# compiler will put a default no-args constructor for instance types but what happens if the class is static? Is the case the same?
What I have tried:
Looking at the Programming Guide on C# for static constructors but didn't find anything related to my question.
推荐答案
查看IL,静态构造函数的唯一时间如果您有静态字段/属性初始值设定项,则为您生成。
Looking at the IL, the only time a static constructor will be generated for you is if you have static field / property initializers.
// No static ctor:
public static class A { }
// Generated static ctor:
public static class B
{
static int answer = 42;
}
// Generated static ctor:
public static class C
{
public static int Answer { get; } = 42;
}
// Explicit static ctor:
public static class D
{
static D()
{
}
}
如果没有字段或属性初始值设定项,并且没有明确的静态构造函数,则不需要静态构造函数。
静态构造函数(C#编程指南)| Microsoft Docs [ ^ ]
这篇关于C#编译器是否放置了默认的静态构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文