gpt4 book ai didi

C# 通用静态构造函数

转载 作者:IT王子 更新时间:2023-10-29 03:49:02 29 4
gpt4 key购买 nike

是否会为传递给泛型参数的每种类型运行泛型类上的静态构造函数,例如:

 class SomeGenericClass<T>
{
static List<T> _someList;
static SomeGenericClass()
{
_someList = new List<T>();
}
}

使用这种方法有什么缺点吗?

最佳答案

是的,静态构造函数将为每个封闭类类型(指定类型参数时创建的类型)调用一次。查看C# 3 specification , §10.12 静态构造函数。

The static constructor for a closed class type executes at most once in a given application domain.

还有:

Because the static constructor is executed exactly once for each closed constructed class type, it is a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile-time via constraints (§10.1.5). For example, the following type uses a static constructor to enforce that the type argument is an enum:

class Gen<T> where T: struct
{
static Gen() {
if (!typeof(T).IsEnum) {
throw new ArgumentException("T must be an enum");
}
}
}

阅读§4.4.2 开放和封闭类型也很重要:

At run-time, all of the code within a generic type declaration is executed in the context of a closed constructed type that was created by applying type arguments to the generic declaration. Each type parameter within the generic type is bound to a particular run-time type. The run-time processing of all statements and expressions always occurs with closed types, and open types occur only during compile-time processing.

Each closed constructed type has its own set of static variables, which are not shared with any other closed constructed types.

这个您可以自己运行的程序演示了静态构造函数被调用了三次,而不仅仅是一次:

public class Program
{
class SomeGenericClass<T>
{
static SomeGenericClass()
{
Console.WriteLine(typeof(T));
}
}

class Baz { }

static void Main(string[] args)
{
SomeGenericClass<int> foo = new SomeGenericClass<int>();
SomeGenericClass<string> bar = new SomeGenericClass<string>();
SomeGenericClass<Baz> baz = new SomeGenericClass<Baz>();
}
}

输出:

System.Int32System.StringProgram+Baz

关于C# 通用静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2936580/

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