7

这让我很困惑。也许我现在太累了。

    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。似乎调试器对我撒了谎,或者其他什么。无论如何,现在工作。谢谢。

4

5 回答 5

1

这似乎是 Visual Studio 调试模式中的一个讨厌的错误,它正在愚弄你:

替代文字

现在F10跨过这条线,你会得到:

替代文字

在控制台上打印正确的值。

哇。

于 2010-08-29T12:15:55.197 回答
0
Rectangle cropArea = (!inputArea.HasValue) ? rectangle : inputArea.Value;
于 2010-08-29T12:04:42.227 回答
0

您的代码显示正确。条件表达式(或条件运算符,或最初称为三元运算符......现在大家都开心吗?:))应该可以与 if/else 语句互换。

Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value;

应该与以下内容完全相同:

Rectangle cropArea;
if (inputArea == null)
{
    cropArea = rectangle;
}
else
{
    cropArea = inputArea.Value;
}

(实际上它们应该生成相同的 IL 代码)。

使用调试器进行跟踪,看看是否有任何问题。

于 2010-08-29T12:05:51.287 回答
0

那么您是说 when inputAreais null,如果没有该if语句,您会得到一个初始化为图像大小以外的其他东西的矩形?我刚刚尝试运行它,它工作正常。确保它image有一个大小,inputArea实际上是null.

于 2010-08-29T12:05:57.280 回答
-1

我勒个去?

Rectangle rectangle = ...;
Rectangle cropArea;
if (inputArea == null)
    cropArea = rectangle;
else
    cropArea = inputArea.Value;

if (inputArea == null)
    cropArea = rectangle;

为什么有第二个if?这是完全和完全多余的。如果 inputArea.Value 为空/零,cropArea 可能仍为空或为零的情况是,因为您没有检查(仅当 inputArea 为空时)。

于 2010-08-29T12:06:06.590 回答