.Net 中条件运算符的奇怪行为
这让我很困惑。也许我现在太累了。
Rectangle rectangle = new Rectangle(0, 0, image.Width, image.Height);
Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value;
if (inputArea == null)
cropArea = rectangle;
inputArea 是一个可以为空的矩形,在我的特定情况下为空。
前两个语句生成一个初始化为 0 的cropArea。然而,第二个语句根据图像宽度和高度生成正确的cropArea。我对条件运算符有什么误解吗?当 inputArea = null 时,它似乎不返回矩形?使用值类型时是否有任何怪癖?
编辑:好吧,我应该先尝试一下:重新启动 VS。看来调试器对我撒了谎,或者什么的。无论如何,现在可以工作了。谢谢。
This has me pretty stumped. Maybe I'm too tired right now.
Rectangle rectangle = new Rectangle(0, 0, image.Width, image.Height);
Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value;
if (inputArea == null)
cropArea = rectangle;
inputArea is a nullable Rectangle, which in my particular case is null.
The first two statements yields a cropArea initialized to 0. The second, however, yields the correct cropArea based on the image width and height. Have I misunderstood anything with the conditional operator? It seems it does not return rectangle when inputArea = null? Is there any quirks when working with value types?
EDIT: Alright, I should have tried this first: restarted VS. It seems the debugger lied to me, or something. Anyway, works now. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这似乎是 Visual Studio 调试模式中的一个令人讨厌的错误,它在愚弄您:
现在 F10 越过这一行,您会得到:
在控制台上打印正确的值。
WTF。
That seems like a nasty bug in Visual Studio debug mode which is fooling you:
Now F10 to step over this line and you get:
On the console correct values are printed.
WTF.
那么您是说,当
inputArea
为null
时,如果没有if
语句,您会得到一个初始化为图像大小以外的值的矩形吗?我刚刚尝试运行它,效果很好。确保image
具有大小,并且inputArea
实际上为null
。So are you saying that when
inputArea
isnull
, without theif
statement you get a rectangle initialized to something else than the image size? I just tried running that and it works fine. Make sure thatimage
has a size and thatinputArea
is actuallynull
.您的代码看起来是正确的。条件表达式(或条件运算符,或最初称为三元运算符...现在大家都高兴了吗?:))应该可以与 if/else 语句互换。
完全相同
应该与:(实际上它们应该生成相同的 IL 代码)
。 使用调试器进行跟踪,看看是否有任何异常。
Your code appears correct. The conditional expression (or conditional operator, or originally called the ternary operator... everyone happy now? :)) should be interchangeable with if/else statements.
should be exactly the same as:
(in fact they should generate the same IL code).
Trace through with the debugger and see if anything jumps out at you.
我勒个去?
为什么要有第二个if?这完全是多余的。 CropArea 可能仍为 null 或零的情况是 inputArea.Value 为 null/0,因为您没有检查这一点(仅当 inputArea 为 null 时)。
What the hell?
Why have the second if? It's totally and entirely redundant. The scenario in which cropArea might still be null or zero is if inputArea.Value is null/zero, since you didn't check for that (only if inputArea is null).