【问题标题】:How to use Code Contracts with query?如何在查询中使用代码合同?
【发布时间】:2009-10-13 12:53:02
【问题描述】:

我对代码合同还很陌生......我遇到了一个问题。

我有一个类似这样的方法 LINQ 查询:

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();

我想在我的项目中实现代码契约。我做的一切都很好,直到我到了这一点。当我运行静态检查器时,它建议我需要添加一些关于在查询中定义的变量 p 和 fAttr 的先决条件(Contract.Requires)。而且,我还有一些未经证实的要求。

我该如何解决这个问题?有什么想法吗?

MyClass 还包含两个前置条件:

internal MyClass(PropertyInfo p, MyClassAttribute att)
    {
        Contract.Requires(p != null);
        Contract.Requires(att != null);
        ...
    }

提前致谢:)

【问题讨论】:

    标签: linq code-contracts


    【解决方案1】:

    我似乎无法重现这一点。您使用的是最新版本的代码合同吗?

    我的整个代码看起来像这样...这与您的版本足够接近吗?

    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();
    
            }
        }
    }
    

    【讨论】:

    • 哦,亲爱的,我刚刚意识到我的 StackOverflow 被过滤为“未回答”的问题,现在已经回答了一段时间的老问题了......:P
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多