令人惊讶的CLR / JIT?行为 - 一个局部变量的初始化推迟惊讶、初始化、变量、局部

2023-09-07 03:03:45 作者:佪亿の唦漏

我刚刚遇到了一些非常奇怪的运行调试模式( VS 2008例preSS的应用程序 CPU的任何)。我想AP preciate,如果有人告诉我,到这里发生了什么?

I have just encountered something quite bizarre running an app in Debug mode (VS 2008 Express, Any Cpu). I would appreciate if someone enlightened me as to what is happening here?

// 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 变量没有任何联系,虽然它的构造的确alocate一些字典

The AutomappingReportArgs class has no connection whatsoever to the sizeIds variable, although its constructor does alocate a number of dictionaries:

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优化的,但我想知道它的机制的更多细节。这究竟是什么延迟初始化的原因是什么?

I guess it must be some sort of compiler or CLR optimization, but I would like to know the mechanism of it in more detail. What is the reason for this "deferred initialization"?

和它为什么不一致的,为什么它马上工作了词典&LT;字符串,INT&GT; ,而不是词典&LT;字符串,字符串&GT ; ?难道是因为编译器看不到任何词典&LT;字符串,INT&GT; 初始化未来,所以不能把它放在一边供以后

And why is it inconsistent, why does it work straight away for Dictionary<string, int>, but not for Dictionary<string, string>? Is it because the compiler can't see any Dictionary<string, int> initialization ahead, so it can't put it aside for later?

推荐答案

这是当你调试优化code pretty的标准行为。不太可能在这里是这样的。很可能是在调试器的一个错误来代替。有一个重要的职位SP1修补程序VS2008是固定的一些调试问题。

This is pretty standard behavior when you debug optimized code. Unlikely to be the case here. Likely to be a bug in the debugger instead. There was an important post SP1 hotfix for VS2008 that fixed a number of debugger problems.

您会发现在的链接修复这个答案。不太确定如何适用该修补程序是防爆preSS版,你应该没问题,但我不能保证这一点。

You'll find the link to the hotfix in this answer. Not so sure how applicable the hotfix is to the Express Edition, you should be okay but I can't guarantee it.

 
精彩推荐
图片推荐