gpt4 book ai didi

c# - 静态集合是否保证在另一个类使用它之前被初始化/填充?

转载 作者:行者123 更新时间:2023-11-30 19:24:16 29 4
gpt4 key购买 nike

假设我有这两个类:

public class A<T> where T : IEntityWithID, new()
{
private static EntityInfo entityInfo = B.GetEntityInfo(typeof(T));

private static IEnumerable TestCases
{
// Do work with entityInfo...
}
}

private static class B
{
private static IList<EntityInfo> entityInfoList = B.GetEntityList();

public static EntityInfo GetEntityInfo(Type type)
{
return entityInfoList.Single(e => e.Types.Contains(type));
}

private static IList<EntityInfo> GetEntityList()
{
// Builds a list of EntityInfo's...
}
}

是否保证在类 A 中调用 B.GetEntityInfo() 之前初始化和填充类 B 中的 entityInfoList?

最佳答案

是的,这是有保证的。这是来自 MSDN 的片段:

The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program.

编辑:如前所述,您最终可能会遇到 2 个静态类相互依赖进行初始化的情况,这可能会给您带来麻烦,但只要不是这种情况,您就没事。

关于c# - 静态集合是否保证在另一个类使用它之前被初始化/填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835926/

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