1

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

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);
    }
}

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

我的问题是在调试和没有调试器的情况下运行时的行为差异:

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

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

4

1 回答 1

5

解决方法是向 Resources 类添加一个静态构造函数:

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

    static Resources()
    {
    }
}

编辑阅读Jon Skeet 的这篇文章

于 2012-07-26T08:37:18.510 回答