gpt4 book ai didi

c# - 为什么不在用作泛型类型参数的类上调用静态构造函数?

转载 作者:可可西里 更新时间:2023-11-01 08:46:48 24 4
gpt4 key购买 nike

给定以下类:

public class Foo {
static Foo() {
Console.WriteLine("Foo is being constructed");
}
}

public class Bar {
public void ReferenceFooAsGenericTypeParameter<T>() {
Console.WriteLine("Foo is being referenced as a generic type parameter");
}
}

public class SampleClass
{
public static void Main()
{
new Bar().ReferenceFooAsGenericTypeParameter<Foo>();
}
}

输出是

Foo is being referenced as a generic type parameter

根据规范,这是有道理的:

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

但我很好奇为什么在将类型作为泛型类型参数引用时不调用静态构造函数。

最佳答案

为什么需要这样?

正常调用静态构造函数的要点是确保静态构造函数中设置的任何状态在首次使用之前都已初始化。

仅将 Foo 用作类型参数不会使用其中的任何状态,因此无需调用静态构造函数。

您可能想尝试创建一个带有副作用的静态变量初始值设定项(例如,然后 打印到控制台的方法调用)并删除静态构造函数 - can affect the timing of initialization significantly在某些情况下。它可能在这里触发它。

关于c# - 为什么不在用作泛型类型参数的类上调用静态构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873903/

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