2009-10-13 42 views
0

我對代碼合同相當陌生...而我遇到了一個問題。如何在查詢中使用代碼合同?

我有一個方法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); 
     ... 
    } 

感謝提前:)

回答

0

我似乎無法重現此。您是否使用最新版本的代碼合同?

我的整個代碼看起來像這樣...這是否足夠接近您的版本?

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

     } 
    } 
} 
+1

哦親愛的,剛剛意識到我有我的StackOverflow篩選爲「未回答」的問題,已經回答了一段時間的舊問題...:P – porges 2011-01-19 10:20:58

相關問題