gpt4 book ai didi

c# - 试图理解静态构造函数

转载 作者:太空狗 更新时间:2023-10-29 22:36:31 25 4
gpt4 key购买 nike

我正在尝试了解对静态构造函数的需求。我发现的所有信息都没有回答我提出的问题。你为什么要这样做

class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;

// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
baseline = DateTime.Now.Ticks;
}
}

相对于此

class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline = DateTime.Now.Ticks;

// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
//static SimpleClass()
//{

//}
}

?


这不是其他问题的骗局,这是关于不接受参数的静态构造函数。

最佳答案

需求在某种程度上是显而易见的:您想要为静态成员做的不仅仅是一些字段初始化。

逻辑上如果你有这个类:

class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline = DateTime.Now.Ticks;


}

你可以重写它来达到同样的效果:

class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;

static SimpleClass () {
baseline = DateTime.Now.Ticks;
}
}

但是,您可以在静态构造函数中做更多的事情,例如检查(使用反射)一些属性并向它们发出一些快速访问器/ getter ,或者只是简单地通知其他系统您的类型已创建等。

来自 Jeffrey Richter CLR via C# book:

When the C# compiler sees a class with static fields that use inline initialization (the BeforeFieldInit class), the compiler emits the class’s type definition table entry with the BeforeFieldInit metadata flag. When the C# compiler sees a class with an explicit type constructor (the Precise class), the compiler emits the class’s type definition table entry without the BeforeFieldInit metadata flag. The rationale behind this is as follows: initialization of static fields needs to be done before the fields are accessed, whereas an explicit type constructor can contain arbitrary code that can have observable side effects; this code may need to run at a precise time.

显然,幕后发生的事情远不止这些,我建议您通过 C# 阅读 CLR 的整章:“类型构造函数”

关于c# - 试图理解静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35009200/

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