如何避免"source!= null"使用代码协定和Linq To Sql时? [英] How to avoid "source !=null" when using Code Contracts and Linq To Sql?

查看:459
本文介绍了如何避免"source!= null"使用代码协定和Linq To Sql时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用正常的数据上下文执行以下代码,效果很好:

I have the following code using a normal data context which works great:

var dc = new myDataContext();
Contract.Assume(dc.Cars!= null);
var cars = (from c in dc.Cars
            where c.Owner == 'Jim'
            select c).ToList();

但是,当我将过滤器转换为这样的扩展方法时:

However when I convert the filter to an extension method like this:

var dc = new myDataContext();
Contract.Assume(dc.Cars!= null);
var cars = dc.Cars.WithOwner('Jim');

public static IQueryable<Car> WithOwner(this IQueryable<Car> cars, string owner)
{
    Contract.Requires(cars != null);
    return cars.Where(c => c.Owner == owner);
}

我收到以下警告:

警告:CodeContracts:要求未经证实:source!= null

warning : CodeContracts: requires unproven: source != null

推荐答案

我的猜测是您的警告是由owner参数而不是汽车引起的.在WithOwner方法中添加一个前提条件,以检查owner是否不为空.

My guess is that your warning is caused by the owner parameter, rather than the cars. Add a precondition in the WithOwner method to check if owner is not null.

public static IQueryable<Car> WithOwner(IQueryable<Car> cars, string owner)
{
    Contract.Requires(cars != null);
    Contract.Requires(!string.isNullOrEmpty(owner));
    return cars.Where(c => c.Owner = owner);
}

在您的第一个代码示例中,您已经对"Jim"进行了硬编码,因此那里没有问题,因为没有东西可以为空.

In your first code sample, you have 'Jim' hard-coded, so no problems there because there is not something which can be null.

在第二个示例中,您创建了一个方法,该方法的静态编译器无法证明源(成为所有者)永远不会为null",因为其他代码可能会使用无效值对其进行调用.

In your second example you created a method for which the static compiler cannot prove that the source ( being owner ) 'will never be null', as other code might call it with an invalid values.

这篇关于如何避免"source!= null"使用代码协定和Linq To Sql时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆