静态集合是否保证在另一个类使用之前进行初始化/填充?

And*_*rew 2 c# static

假设我有这两个类:

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...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

its*_*e86 5

是的,它是有保证的.这是MSDN的一个片段:

程序无法准确指定何时加载类.但是,保证在程序中第一次引用类之前,可以加载并初始化其字段并调用其静态构造函数.

编辑:正如所指出的那样,你可能最终会出现这样一种情况,即2个静态类相互依赖进行初始化,这可能会让你遇到麻烦,但只要不是这样,你就没事了.