静态元素的执行顺序初始化

Raf*_*fal 1 c# static .net-4.0

我遇到过像这样的设置代码:

internal class Something
{
    public string Name { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

internal static class Factory
{
    public static string Name { get; set; }

    public static Something Create()
    {
        return new Something { Name = Name };
    }
}

internal static class Resources
{
    public static readonly Something DefaultSomething = Factory.Create();
}

internal class Program
{
    public static void Main(string[] args)
    {
        Factory.Name = "MyFactory";
        Execute();
        Console.ReadKey();
    }

    private static void Execute()
    {
        Console.WriteLine(Resources.DefaultSomething);
    }
}
Run Code Online (Sandbox Code Playgroud)

当然这只是一个片段,我不想详细说明为什么这样做.

我的问题是在调试和没有调试器的发布中运行时的行为差异:

  • 使用调试器调试或释放:MyFactory打印到控制台
  • 不带调试器的释放:打印空行

显然,问题在于静态元素的执行顺序初始化以及在发布模式下编译时完成的一些优化.我想知道如何在不制动这种设置的情况下解决这个问题.

huy*_*itw 5

修复是向Resources类添加一个静态构造函数:

internal static class Resources
{
    public static readonly Something DefaultSomething = Factory.Create();

    static Resources()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑阅读Jon Skeet 撰写的这篇文章