简体   繁体   English

在 C# 中的 Try-Catch 块中返回一个布尔值

[英]Returning a bool value inside Try-Catch block in C#

 public bool RemoveProduct(int id)
        {
            // code to remove product by the id provided as parameter
            try 
            {
                var prod = productlist.Where(s => s.ProductId == id).FirstOrDefault();
                productlist.Remove(prod);
            }
            catch (Exception) 
            {
                return false;
            }
            return true;
            

        }

I tried to call the function RemoveProduct(id) with parameter Id which is not present in the productlist, it should return false but it is always returning true no matter what.我尝试使用产品列表中不存在的参数 Id 调用 function RemoveProduct(id),它应该返回 false,但无论如何它总是返回 true。 How to solve this problem and return false when the product with the given id isn't in the list?当具有给定 id 的产品不在列表中时,如何解决此问题并返回 false?

This is because neither FirstOrDefault() or Remove() will throw an exception when not finding a value in your list.这是因为在列表中找不到值时, FirstOrDefault()Remove()都不会引发异常。

You could either return false if you didn't find your item ( prod == null ).如果您没有找到您的项目,您可以返回 false ( prod == null )。

Or just return the result of Remove() (though if you have a null item and did not find an item with the provided id, you'd end up removing it and returning true either way)或者只是返回Remove()的结果(尽管如果你有一个 null 项目并且没有找到具有提供的 id 的项目,你最终会删除它并以任何方式返回 true)

As it is right now, the only case where your method would return false is when your list is null, resulting in a NullReferenceException就像现在一样,您的方法返回 false 的唯一情况是当您的列表是 null 时,会导致NullReferenceException

I would do something like this, if you really want a true/false return.如果你真的想要一个真/假的回报,我会做这样的事情。

public bool RemoveProduct(int id)
{
    // code to remove product by the id provided as parameter
    var prod = productlist.Where(s => s.ProductId == id).FirstOrDefault();
 
    if (prod == null) return false;        

    productlist.Remove(prod);

    return true;
}
       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM