VS调试问题,谁能帮我在下面解释一下? [英] VS debug issue, who can help me to explain this below?
问题描述
一段C#代码
var isTrue = (new List<int>{1,2,3} is IEnumerable<object>);
我在代码执行中得到结果 false
,
,但是当我将该代码复制到WATCH窗口中时,结果为 true
。
I got result false
in code execution,
but when I copy that code into WATCH window, the result is true
.
推荐答案
这不是一个完整的答案(我不知道此错误出现的原因),但它为调试器的不稳定行为(显然是错误的)提供了一些线索。
This is not a complete answer (I don't know the reasons why this bug is cropping up), but it sheds some light on the erratic behaviour of the debugger which is obviously buggy.
首先,C#禁止(也包括AFAIK和CLR)类型方差卷积值类型;仅当所涉及的类型之间存在标识保留转换时才允许方差,否则方差将失败(值类型没有标识保留转换):
First and foremost: C# disallows (and AFAIK, the CLR too) type variance involvig value types; variance is only allowed if there is an identity preserving conversion between the involved types, otherwise it will fail (there is no identity preserving conversion for value types):
object[] oo = new int[] {1, 2, 3}; //will fail
IEnumerable<object> oo = new int[] {1, 2, 3}; //will fail
调试器的即时窗口显然是错误的, new List< int> {1,2,3}是IEnumerable< object>
应该像运行时一样返回 false
。为什么返回 true
?
The debugger's immediate window is obviously wrong, new List<int> { 1, 2, 3 } is IEnumerable<object>
should return false
as the runtime does. Why is it returning true
? Because there's a bug, period.
更令人困惑的是, new int [] {1,2,3}是当
将正确返回 int []
隐式转换为<$时,IEnumerable< object> false
code> IEnumerable< int> 与 List< int>
相同。
What makes it even more bewildering is the fact that new int[] { 1, 2, 3 } is IEnumerable<object>
will correclty return false
when int[]
is implicitly convertible to IEnumerable<int>
same as List<int>
.
我发现后一种正确行为的唯一原因是编译器已经将该表达式标记为始终 false
警告,因此编译器分析数组方案的方式不同于任何其他 IEnumerable
。
The only reason I find for the latter correct behavior is that the compiler already flags that expression as always false
with a warning and therefore the way the compiler analyzes the array scenario is different from any other IEnumerable
.
这篇关于VS调试问题,谁能帮我在下面解释一下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!