Linq 如何将代码契约与查询一起使用?
我对代码合同相当陌生……我遇到了一个问题 我在LINQ查询中使用了如下方法:Linq 如何将代码契约与查询一起使用?,linq,code-contracts,Linq,Code Contracts,我对代码合同相当陌生……我遇到了一个问题 我在LINQ查询中使用了如下方法: MyClass[] fields = (from p in rType.GetProperties() where p.CanRead let fAttr = p.GetCustomAttributes(typeof(MyClassAttribute), true).SingleOrDefault() as MyClassAttribute
MyClass[] fields =
(from p in rType.GetProperties()
where p.CanRead
let fAttr = p.GetCustomAttributes(typeof(MyClassAttribute), true).SingleOrDefault() as MyClassAttribute
where fAttr != null
select new MyClass(p, fAttr)).ToArray();
我想在我的项目中实现代码契约。我做的一切都很好,直到我做到这一点。当我运行staticchecker时,它向我建议需要添加两个前提条件Contract.Requires关于查询中定义的变量p和fAttr。另外,我还有一些未经证实的要求
我怎样才能解决这个问题?有什么想法吗
MyClass还包含两个前提条件:
internal MyClass(PropertyInfo p, MyClassAttribute att)
{
Contract.Requires(p != null);
Contract.Requires(att != null);
...
}
提前感谢:我似乎无法重现这一点。您是否使用最新版本的代码契约 我的整个代码看起来像这样。。。这和你的版本足够接近吗
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
namespace ConsoleApplication10
{
class Program
{
class MyClassAttribute : Attribute{}
class MyClass
{
internal MyClass(PropertyInfo p, MyClassAttribute a)
{
Contract.Requires(p != null);
Contract.Requires(a != null);
}
}
static void Main(string[] args)
{
var rType = typeof (DateTime);
MyClass[] result = (from p in rType.GetProperties()
where p.CanRead
let fAttr = p.GetCustomAttributes(typeof(MyClassAttribute), true).SingleOrDefault() as MyClassAttribute
where fAttr != null
select new MyClass(p, fAttr)).ToArray();
}
}
}
哦,天哪,我刚刚意识到我的问题被过滤成了未回答的问题,已经回答老问题有一段时间了…:P