c# - 代码契约和 MVVM

标签 c# mvvm code-contracts

我在 C# 中有一个 MVVM 项目,我想在其中使用代码契约。 所以这是我的场景: 界面:

public interface IC042_Model
{
    void Save(C042 entity);
    void Delete(C042 entity);
}

然后我有契约(Contract)的抽象类:

[ContractClassFor(typeof(IC042_Model))]
internal abstract class C042_Model_Contracts : IC042_Model
{
    public void Save(C042 entity)
    {
        Contract.Requires(entity != null);
    }

    public void Delete(C042_CondicaoPagamento entity)
    {
        Contract.Requires(entity != null);
    }
}

在另一个项目中,我的模型实现了接口(interface),如果我调用 这个。保存(空) 在任何方法中,都会生成警告。 在我的 ViewModel 中,如果我调用上面的相同方法:this.Save(null),不会生成警告,但是当我运行应用程序时,上面的行会引发 Contract 异常。

我的做法有什么问题吗?

提前致谢。

我再举一个例子,我觉得大家会更容易理解:

我在类库项目中创建了以下类:

public static class StringExtensions
{
    public static string TrimAfter(string value, string suffix)
    {
        Contract.Requires(suffix != (string)null);
        Contract.Requires(!string.IsNullOrEmpty(suffix));
        Contract.Requires(value != null);

        var index = value.IndexOf(suffix);

        if (index < 0)
            return value;

        return value.Substring(0, index);
    }
}

当我从如下所示的 WPF 项目中调用它时:

CodeDigging.StringExtensions.TrimAfter(null, null);

我没有收到关于契约(Contract)不是全场的警告。

这是我的问题,我希望它现在变得更清楚了。

谢谢。

最佳答案

我认为您错过了接口(interface)上的 ContractClass 属性:

[ContractClass(typeof(C042_Model_Contracts)]
public interface IC042_Model 
{ 
    void Save(C042 entity); 
    void Delete(C042 entity); 
} 

关于代码契约有很好的描述here

关于c# - 代码契约和 MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10691476/

相关文章:

c# - 合并 PDF iTextSharp

c# - 验证失败时禁用保存按钮

c# - 共享接口(interface)的数据绑定(bind)错误

.net 4.0 代码契约(Contract)。什么时候使用?他们什么时候浪费时间了?

msbuild - 在使用 MSBuild 构建的库代码中使用代码契约

C# POST 到 OAUTH2 与 formdata

c# - 在C#中将位图图像保存为灰度图像

c# - 私有(private)静态只读字段上的代码契约(Contract)和失败

c# - 如何将多个表数据结构合并到一个表结果结构中?

c# - WPF:如果为 Null,则更改 DataContext?