我有一个返回ItemCollection的方法,如果没有提供信息,我希望尽早停止函数。我通常会通过返回来完成这个任务;但是,正如我的方法所期望的那样,ItemCollection失败了。我把这当成了一件工作,但坦白地说,这似乎很烦人。我是不是错过了什么。我试着返回;我不想抛出异常。
    private ItemCollection loadLeft_Click(object sender, RoutedEventArgs e)
    {
        var leftUser = UsrLeft.Text;
        if (leftUser == "")
        {
            MessageBox.Show("No User Entered");
            GroupListLeft.Items.Add("");
            var fail = GroupListLeft.Items;
            return fail;
        }
        //Succesful test do stuff 
        var leftItems = GroupListLeft.Items;
        return leftItems;
     }发布于 2019-11-15 10:30:43
你没有什么选择:
Exception (甚至可能是像NoUserEnteredException("someText")这样的自定义Exception)。null最后一个是更好的选择,在这种情况下,您不需要在客户端代码中编写空检查或尝试捕获部分。
发布于 2019-11-15 10:36:23
您将需要返回等同于ItemCollection的内容,这取决于您可能希望调用过程如何处理这样的返回,您可以使用null返回:
    if (leftUser == "")
    {
        MessageBox.Show("No User Entered");
        return null;
    }或者返回一个新的ItemCollection。
    if (leftUser == "")
    {
        MessageBox.Show("No User Entered");
        return new ItemCollection();
    }发布于 2019-11-15 10:33:10
您将需要返回null,如
private ItemCollection loadLeft_Click(object sender, RoutedEventArgs e)
{
    var leftUser = UsrLeft.Text;
    if (leftUser == "")
    {
        MessageBox.Show("No User Entered");
        return null;
    }
    //Succesful test do stuff 
    var leftItems = GroupListLeft.Items;
    return leftItems;
 }https://stackoverflow.com/questions/58874999
复制相似问题