令人惊讶的CLR / JIT?行为 - 本地变量的延迟初始化

时间:2012-03-08 10:13:46

标签: c# debugging .net-3.5 clr jit

我刚刚在Debug模式(VS 2008 ExpressAny Cpu)中遇到了一些非常奇怪的应用程序。如果有人开悟我在这里发生了什么,我将不胜感激?

// PredefinedSizeGroupMappings is null here
Dictionary<string, int> groupIDs = PredefinedSizeGroupMappings ?? new Dictionary<string, int>();

// so groupIDs is now initialized as an empty Dictionary<string, int>, as expected

// now: PredefinedSizesMappings is null here - therefore I expect sizeIds
// to be initialized as an empty dictionary:
Dictionary<string, string> sizeIds = PredefinedSizesMappings ?? new Dictionary<string, string>(); 

// but at this point sizeIds is still null! :O That's what debugger shows.
var groupsReport = new AutomappingReportArgs();

// only once we get here - it's suddenly not... The debugger shows: "Count = 0"
var sizesReport = new AutomappingReportArgs();

AutomappingReportArgs类与sizeIds变量没有任何关联,尽管它的构造函数确实放置了许多字典:

public AutomappingReportArgs()
{
    ChangedNames = new Dictionary<string, KeyValuePair<string, string>>();
    CreatedAfterRename = new Dictionary<string, string>();            
    Existing = new Dictionary<string, string>();
    Created = new Dictionary<string, string>();
    Failed = new Dictionary<string, string>();
}

我想它必须是某种编译器或CLR优化,但我想更详细地了解它的机制。这种“延迟初始化”的原因是什么?

为什么它不一致,为什么它会立即用于Dictionary<string, int>,而不用于Dictionary<string, string>?是因为编译器无法提前看到任何Dictionary<string, int>初始化,所以它不能暂时放在一边吗?

1 个答案:

答案 0 :(得分:2)

调试优化代码时,这是非常标准的行为。不太可能是这里的情况。可能是调试器中的错误。 VS2008有一个重要的SP1修补程序修复了许多调试器问题。

您将在this answer中找到指向此修补程序的链接。不太确定此修补程序适用于Express Edition的方式,你应该没问题,但我无法保证。