【发布时间】:2019-02-13 18:32:26
【问题描述】:
对于这么简单的问题,我很抱歉(我已经用谷歌搜索过,但我很困惑,对编程很陌生)
下面的示例代码
public Point GetRandomWalkableLocationInRoom(Rectangle room)
{
if (DoesRoomHaveWalkableSpace(room))
{
for (int i = 0; i < 100; i++)
{
int x = Game.Random.Next(1, room.Width - 2) + room.X;
int y = Game.Random.Next(1, room.Height - 2) + room.Y;
if (IsWalkable(x, y))
{
return new Point(x, y);
}
}
}
return null;
}
【问题讨论】:
-
只需将方法的返回类型更改为
Point?。阅读更多关于它的信息here。 -
您不能从此方法返回 null。错误在这里:返回null;你应该总是返回 new Point();或在发生错误时抛出异常。但是你不能返回 null 因为没有办法将 null 转换为 Point()
-
谢谢,我已经输入了 new Point();这已经成功了!愚蠢的我!
-
返回
new Point();似乎会引入一个错误。找不到可步行点返回0、0真的有效吗?
标签: c# non-nullable