[英]Not all code paths return a value
I am having this Linq To SQL
query which is taking Customer Category from database
.The CustCategory will be defined already.Here is the query. 我有这个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;
}
}
}
Currently I am getting an error that Not all code paths return a value.
当前,我收到一个错误, Not all code paths return a value.
If I am always certain that the value is there in the database then do I need to check for null
,If I need to check for null
then how do I handle this. 如果我始终确定数据库中存在该值,那么我需要检查是否为null
,如果我需要检查是否为null
那么该如何处理。 Can anyone help me with this. 谁能帮我这个。 Any suggestions are welcome. 欢迎任何建议。
Since Enumerable.ToList
never returns null
(see the Return Value section of the documentation ), you can safely remove the if
. 由于Enumerable.ToList
从不返回null
(请参见文档的“ 返回值”部分),因此可以安全地删除if
。
EDIT: Note that, no matter what your database contains, acctype
will never be null: 编辑:请注意,无论您的数据库包含什么, acctype
永远不会为null:
null
). 如果在数据库中找不到值,则返回值将是一个空列表 (不同于null
)。 null
. 列表本身仍然不为 null
。 This is not about LINQ to SQL, the method GetAccountType()
must return IList<string>
. 这与LINQ to SQL GetAccountType()
,方法GetAccountType()
必须返回IList<string>
。 You should return return acctype;
您应该返回return acctype;
and then check this returned list later using Any()
, something like: 然后稍后使用Any()
来检查此返回列表,如下所示:
if(GetAccountType.Any()){
//not empty
}
How about something like this for a fairly clean and readable solution?: 这样的事情对于一个干净整洁的解决方案又如何呢?
( Note, updated: removed the check for null, since it would clearly not have any effect). ( 注意,已更新:删除了对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;
}
What happens if: 如果发生以下情况,会发生什么情况:
if (acctype != null)
Is null? 一片空白? What is your method supposed to return
? 您应该return
什么方法?
You need to return something 你需要退货
You need to return a value from your function: 您需要从函数中返回一个值:
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.