繁体   English   中英

并非所有代码路径都返回值

[英]Not all code paths return a value

我有这个Linq To SQL查询,它从database获取客户类别.CustCategory已经定义好了。这是查询。

public IList<string> GetAccountType()
        {
            using (var db = new DataClasses1DataContext())
            {
                var  acctype = db.mem_types.Select(account=>account.CustCategory).Distinct().ToList();
                if (acctype != null)
                {
                    return acctype;
                }
            }

        }

当前,我收到一个错误, Not all code paths return a value. 如果我始终确定数据库中存在该值,那么我需要检查是否为null ,如果我需要检查是否为null那么该如何处理。 谁能帮我这个。 欢迎任何建议。

由于Enumerable.ToList从不返回null (请参见文档的“ 返回值”部分),因此可以安全地删除if

编辑:请注意,无论您的数据库包含什么, acctype 永远不会为null:

  • 如果在数据库中找不到值,则返回值将是一个空列表 (不同于null )。
  • 如果找到一条记录,并且其值为空,则返回值将是具有一个条目的有效列表 ,其值为空。 列表本身仍然不为 null

这与LINQ to SQL GetAccountType() ,方法GetAccountType()必须返回IList<string> 您应该返回return acctype; 然后稍后使用Any()来检查此返回列表,如下所示:

if(GetAccountType.Any()){
     //not empty
}

这样的事情对于一个干净整洁的解决方案又如何呢?

注意,已更新:删除了对null的检查,因为它显然没有任何作用)。

public IList<string> GetAccountType()
{
        var acctype = new List<string>();
        using (var db = new DataClasses1DataContext())
        {
            acctype = db.mem_types.Select(
                         account=>account.CustCategory).Distinct().ToList();
        }

        return acctype;
    }

如果发生以下情况,会发生什么情况:

if (acctype != null)

一片空白? 您应该return什么方法?

你需要退货

您需要从函数中返回一个值:

    public IList<string> GetAccountType()
            {
                using (var db = new DataClasses1DataContext())
                {
                    var  acctype = db.mem_types.Select(account=>account.CustCategory).Distinct().ToList();
                    if (acctype != null)
                    {
                        return acctype;
                    }
                }
                return acctype;
            }

暂无
暂无

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

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