根据内部方法调用的结果停止进一步执行的方法

时间:2013-02-25 11:00:08

标签: c# .net

情节是这样的 - 我有一个Save()方法,它调用自己的验证方法,我想确保如果验证方法发现错误,Save()方法的执行将停下来我所做的是为验证制作bool方法:

protected virtual bool IsNullOrEmptyControl(params Control[] controls)
        {
            bool validationFlag = false;
            foreach (Control ctrl in controls)
            {
                if (string.IsNullOrWhiteSpace(ctrl.Text))
                {
                    ctrl.BackColor = System.Drawing.Color.Yellow;                
                    if (validationFlag == false)
                    {
                        ctrl.Focus();
                        validationFlag = true;
                    }
                }
            }
            if (validationFlag == true)
            {
                MessageBox.Show("The fields in yellow could not be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

使用我的Save()方法调用它:

public bool Save()
{
some code...
IsNullOrEmptyControl(txtClientCode, txtClientName);
some code..
clientService.Save(entity);
}

我认为是因为我的IsNullOrEmptyControl()方法bool如果它返回false,那么这将意味着停止在Save()中进一步执行代码,但似乎我错了。那么这样做的正确方法是什么?

4 个答案:

答案 0 :(得分:1)

IsNullOrEmptyControl方法只返回值。 您应该在我们的代码中检查此值并对其做出反应

bool checkResult = IsNullOrEmptyControl(txtClientCode, txtClientName);
if(checkResult == false)
{
    return false;
}
some code..
clientService.Save(entity);

答案 1 :(得分:0)

我认为代码应该是:

public bool Save()
{
  some code...
    if(IsNullOrEmptyControl(txtClientCode, txtClientName)) {  
      some code..
      clientService.Save(entity);
    }
}

答案 2 :(得分:0)

您应该在保存调用中创建if语句。如果IsNullOrEmptyControl返回false,则不会执行clientService.Save(entity);

public bool Save()
{
    //some code...
    if(IsNullOrEmptyControl(txtClientCode, txtClientName))
    {
        //some code..
        clientService.Save(entity);
    }
}

答案 3 :(得分:0)

您应该将验证方法的返回值分配给变量并在调用clientService.Save()之前进行检查。

此外,您可能希望在上方foreach循环中放置一个中断,就在您将旗帜设置为true的行下方。

相关问题