[英]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.