c# - 通用接口(interface)上的代码约定问题

标签 c# .net generics interface code-contracts

我遇到了一个涉及通用接口(interface)契约(Contract)的问题。我有两个通用接口(interface),每个接口(interface)都有一个方法,该方法有一个前提条件(Requires 契约)。第一个接口(interface)的契约按预期工作:先决条件被传播到实现类,并且接口(interface)方法被适本地修饰(通过代码契约编辑器扩展)。未检测到第二个接口(interface)的契约(Contract),但两个接口(interface)/契约(Contract)对之间的代码几乎相同。

//
// 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.* 中的任何接口(interface)都会导致此行为。使用任何其他类型,一切都按预期工作。但是,我不知道这是为什么。

编辑:Porges pointed out ,契约(Contract)正在编写(通过 IL 确认),因此这似乎特定于代码契约(Contract)编辑器扩展。

最佳答案

我无法复制这个。鉴于此代码(以及您的示例):

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

合约按预期传播(通过 Reflector 反编译):

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

关于c# - 通用接口(interface)上的代码约定问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9102059/

相关文章:

c# - ANTLR4 与 Unity3D

c# - 使用 System.IO.Packaging 在 C# 中创建 zip

c# - 如何使用 PropertyInfo.SetValue Method (Object, Object) 设置可空属性的值

c# - 使用 Type 参数实例化泛型集合

c# - RadComboBox 选中的值为空

c# - 可以在 LINQ 中按计数分组吗?

c# - ASP Repeater 没有以正确的顺序显示数据

.net - WPF中的键盘焦点与逻辑焦点

c# - 界面中发生了什么?

C# 如何将从 linq 返回的对象分配给 'this' 引用?