【问题标题】:"is" operator works differently in Immediate Window for boxed values"is" 运算符在即时窗口中对装箱值的工作方式不同
【发布时间】:2018-02-16 06:12:15
【问题描述】:

对于盒装的int,例如object boxedInt = 0 在您的代码中定义,is objectis int 在 Visual Studio 的即时窗口中返回 false。这是一个错误,不是吗?

代码:

int normalInt = 0;

Debug.WriteLine(normalInt.GetType().FullName); // System.Int32
Debug.WriteLine(normalInt is object);          // true
Debug.WriteLine(normalInt is int);             // true
Debug.WriteLine(normalInt is System.Int32);    // true

object boxedInt = 0;

Debug.WriteLine(boxedInt.GetType().FullName); // System.Int32
Debug.WriteLine(boxedInt is object);          // true
Debug.WriteLine(boxedInt is int);             // true
Debug.WriteLine(boxedInt is System.Int32);    // true

立即窗口:

normalInt.GetType().FullName
"System.Int32"
normalInt is object
true
normalInt is int
true
normalInt is System.Int32
true

boxedInt.GetType().FullName
"System.Int32"
boxedInt is object
false                                         // WTF?
boxedInt is int
false                                         // WTF?
boxedInt is System.Int32
false                                         // WTF?

object boxedInt2 = 0;
Expression has been evaluated and has no value
boxedInt2.GetType().FullName
"System.Int32"
boxedInt2 is object
true
boxedInt2 is int
true
boxedInt2 is System.Int32
true

Microsoft Visual Studio 企业版 2017
版本 15.3.3
VisualStudio.15.Release/15.3.3+26730.12

Microsoft .NET 框架
版本 4.7.02046

Visual C# 2017 00369-60000-00001-AA135


Watch 窗口截图:

【问题讨论】:

  • 是的。例如,在上述代码之后设置断点时。
  • 我认为你必须这样做-boxedInt == typeof(object);
  • @SouvikGhosh boxedInt 不是 Type 对象,所以这永远不会是真的。
  • @Sinatr is 不需要左侧的类型。如果您使用 == 运算符将某些内容与 Type 进行比较,那么 that 就是您需要 Type 的时候。
  • 我认为这是由于即时窗口运行的沙箱。窗口中的Object 与应用程序中的Type 不同,即使全名是一样的。如果你在即时窗口中执行typeof(Object) == (boxedInt.GetType()),它会返回 false。

标签: c# types visual-studio-debugging


【解决方案1】:

在Tools->Option->Debugging下,请启用“Use the legacy C# and VB expression evaluators”选项,再次调试。

更新:

此问题已在此处报告:

https://developercommunity.visualstudio.com/content/problem/31283/and-operation-of-boolean-is-wrong.html

【讨论】:

  • 这是一个有用的答案,因为它确实有效。但是,它没有回答为什么您希望在非传统(即应该更好)模式下观察到的行为以及这是否可能是一个错误。我对此投了赞成票,但不接受它作为正确答案。
  • @Marco Eckstein,我会报告这个问题并与其他成员讨论,如果我有任何最新信息,我会在这里分享。
  • @Marco Eckstein,类似问题已在此处报告:developercommunity.visualstudio.com/content/problem/31283/…,产品团队成员将跟进,您也可以在此处分享您的评论。
猜你喜欢
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
相关资源
最近更新 更多