2016-06-20 47 views
2

我有以下代码,并想知道为什么其他部分无法访问resharper。resharper警告代码启发式无法访问

private bool SomeMEthod(some parameter) 
{ 
    bool status = false; 
    var someCollection = _entity.CustomerPaymentStatus.Where(record => record.CustomerPaymentId == paymentId && record.CurrentRecord == true); 
    if (someCollection != null) 
    { 
     var receivedPayment = someCollection.FirstOrDefault(); 
     /*some code to save data into DB*/ 
     status = true; 
    } 
    else 
    { 
     //Some code here to log failure scenario 

     //here Resharper giving me warning 
     //code is heuristically unreachable 
    } 
    return status; 
} 

我检查了几个岗位,但并不清楚像Code is heuristically unreachable

任何思想请。

+4

'Where'永远不应该返回'null'但可能会返回一个空的序列,那么你的'if'条件将始终评估为TRUE;。 – Lee

回答

5

.Where()永远不会返回null,但总是返回IEnumerable<T>(或IQueryable<T>。可枚举可能有0项,但它仍然是一个非空的枚举。

+0

如果'_entity.CustomerPaymentStatus'为null,那么将会抛出异常,并且将不会到达else。 –

+0

@KooKiz:是的,当然。但是'NullReferenceException'是一个完全不同的问题;) – knittl

2

LINQ的Where查询将返回一个空IEnumerable如果没有符合条件的记录被发现,所以它是非常unlikly是someCollection将永远是null - 虽然ReSharper的似乎并没有完全地被肯定了。

另见MSDN Where

0

假设_entity是的DbContext又在哪里总是返回一个IQueryable对象。

IQueryable<T> someCollection = _entity.CustomerPaymentStatus.Where(...); 

这IQueryable的对象永远不能为null(否则你将无法进行查询)。

测试该对象为空doe不执行查询。所以

if (someCollection != null) 

相同

if (true)