1

我有一个船泊位预订程序,目前,它的工作方式是,在您输入您的姓名并单击一个按钮后,该程序会为您提供下一个可用的停泊处,有 6 个码头,每个码头有 5 个停泊处。

所以,在所有的系泊和码头都用完之后,程序崩溃了,因为它无处可去,我怎样才能让它让用户得到一个消息框告诉他们,没有更多的可用位置?

这是我的代码:

按钮点击:

private void button1_Click(object sender, EventArgs e)
{
    var req = new BoatRequest();
    req.Name = txtName.Text;
    var client = new BoatReserveSoapClient();
    BoatResponse response = client.ReserveMooring(req);

    if (req != null)
    {
        Pierlbl.Text = response.Pier.ToString();
        Mooringlbl.Text = response.Mooring.ToString();
        Pierlbl.Visible = true;
        Mooringlbl.Visible = true;
    }
    else
    {
        Pierlbl.Text = "Error Occured, please try again";
        Mooringlbl.Text = "Error Occured, please try again";
    }
}

网络方法:

//Setting the max value for Piers and Moorings
public const int maxPiers = 6;
public const int maxMoorings = 30;
private static bool[,] reserveMooring = new bool[maxPiers, maxMoorings];

[WebMethod]
public BoatResponse ReserveMooring(BoatRequest req)
{
    var res = new BoatResponse();

    //if pierCalc set to 0, if smaller than maxPiers increment
    for (int pierCalc = 0; pierCalc < maxPiers; pierCalc++)
    {
        //if mooringCalc set to 0, if smaller than maxMoorings increment
        for (int mooringCalc = 0; mooringCalc < maxMoorings / maxPiers; mooringCalc++)
        {
            if (!reserveMooring[pierCalc, mooringCalc])
            {
                reserveMooring[pierCalc, mooringCalc] = true;
                res.Pier = (Pier)pierCalc;
                res.Mooring = (Mooring)mooringCalc;
                return res;
            }
        }
    }
    return null;
}

这是它崩溃的地方:

Pierlbl.Text = response.Pier.ToString();
4

3 回答 3

2

Check that the response is not null, like this:

if (response != null)
{
    Pierlbl.Text = response.Pier.ToString();
    Mooringlbl.Text = response.Mooring.ToString();
    Pierlbl.Visible = true;
    Mooringlbl.Visible = true;
}
else
{
    Pierlbl.Text = "Error Occured, please try again";
    Mooringlbl.Text = "Error Occured, please try again";
}
于 2013-10-28T14:11:45.480 回答
0

In this example, req is never going to equal null. the response object is receiving the return value from your Web Service and would therefore the one to check for a null value in your if statement.

Like so:

 if (response != null)
        {
            //Logic for success
        }
        else
        {
            //Logic for failure
        }
于 2013-10-28T14:19:14.550 回答
0

您应该只检查 response != null 如果是这种情况,则向用户显示一条消息。

于 2013-10-28T13:59:49.567 回答