2012-02-01 19 views
3

我遇到涉及通用接口合同的問題。我有兩個通用接口,每個接口都有一個單一的前提條件(Requires合同)。第一個接口的合同按預期工作:先決條件傳播到實現類,接口方法適當地進行了修飾(通過代碼合同編輯器擴展)。未檢測到第二個接口的合同,但兩個接口/合同對之間的代碼幾乎相同。通用接口上的代碼合同問題

// 
// Example working as expected 
// 

[ContractClass(typeof(IExporterContract<>))] 
public interface IExporter<in TInput> 
    where TInput : class 
{ 
    // Shows adornment "requires obj != null"; contracts propogate 
    void Export(TInput obj); 
} 

[ContractClassFor(typeof(IExporter<>))] 
abstract class IExporterContract<TInput> : IExporter<TInput> 
    where TInput : class 
{ 
    public void Export(TInput obj) 
    { 
     Contract.Requires(obj != null); 
    } 
} 


// 
// Example with unexpected behavior 
// 

[ContractClass(typeof(IParserContract<>))] 
public interface IParser<out TOutput> 
    where TOutput : class 
{ 
    // Workbook is Microsoft.Office.Interop.Excel.Workbook 

    // Does not show adornment "requires workbook != null"; contracts do not propogate 
    TOutput Parse(Workbook workbook); 
} 

[ContractClassFor(typeof(IParser<>))] 
abstract class IParserContract<TOutput> : IParser<TOutput> 
    where TOutput : class 
{ 
    public TOutput Parse(Workbook workbook) 
    { 
     Contract.Requires(workbook != null); 
     return default(TOutput); 
    } 
} 

值得注意的是,Microsoft.Office.Interop.*中的任何接口都會導致此行爲。使用任何其他類型,一切都按預期工作。然而,我不知道這是爲什麼。

編輯:作爲Porges pointed out,合同正在編寫(通過IL確認),所以這似乎是特定於代碼合同編輯器擴展。

回答

2

我無法複製這個。鑑於這種代碼(連同你的例子):

class Program 
{ 
    static void Main(string[] args) 
    { 
     var g = new Bar(); 
     g.Parse(null); 
     var f = new Foo(); 
     f.Export(null); 
    } 
} 

public class Foo : IExporter<Foo> 
{ 
    public void Export(Foo obj) 
    { 
    } 
} 
public class Bar : IParser<Bar> 
{ 
    public Bar Parse(Workbook workbook) 
    { 
     return null; 
    } 
} 

合同傳播如預期(通過反射反編譯):

public Bar Parse(Workbook workbook) 
{ 
    __ContractsRuntime.Requires(workbook != null, null, "workbook != null"); 
    return null; 
} 
+0

你是對的,但它顯示了在IL;我沒有檢查。你是否安裝了Code Contracts Editor Extension?我很想看看合約裝飾是否適合你。 – 2012-02-01 21:20:28

+1

它沒有顯示任何'Parse'。但是,當我將鼠標移到'Export'上時,它會顯示「此會員沒有合同」,這很奇怪。也許有一些與最新的CC版本不兼容? – porges 2012-02-01 22:04:03