为什么不能在覆盖方法中添加Contract.Requires? [英] Why can't I add Contract.Requires in an overriden method?

查看:666
本文介绍了为什么不能在覆盖方法中添加Contract.Requires?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用代码契约(实际上,使用这个学习)。

I'm using code contract (actually, learning using this).

我面对一些奇怪的事情...我重写了一个方法,第三方程序集。我想添加 Contract.Require 语句,如下所示:

I'm facing something weird to me... I override a method, defined in a 3rd party assembly. I want to add a Contract.Require statement like this :

public class MyClass: MyParentClass
{
    protected override void DoIt(MyParameter param)
    {
        Contract.Requires<ArgumentNullException>(param != null);

        this.ExecuteMyTask(param.Something);
    }

    protected void ExecuteMyTask(MyParameter param)
    {
        Contract.Requires<ArgumentNullException>(param != null);
        /* body of the method */
    }
}

但是,我得到这样的警告:

However, I'm getting warnings like this :


警告1 CodeContracts:
方法'MyClass.DoIt(MyParameter)'覆盖'MyParentClass.DoIt(MyParameter))',因此不能添加Requires。

Warning 1 CodeContracts: Method 'MyClass.DoIt(MyParameter)' overrides 'MyParentClass.DoIt(MyParameter))', thus cannot add Requires.

代码有点显示替代问题 [/ edit]

如果我删除 Contract.Requires 在DoIt方法,我得到另一个警告,告诉我,我必须提供未经证实 param!= null
我不明白这个警告。

If I remove the Contract.Requires in the DoIt method, I get another warning, telling me I have to provide unproven param != null I don't understand this warning. What is the cause, and can I solve it ?

推荐答案

您不能添加呼叫者可能不知道的额外要求中。它违反了 Liskov的取消原则。多态性的观点是,调用者应该能够处理实际上指向你的派生类的实例的引用,就像引用基类的实例一样。

You can't add extra requirements which your callers may not know about. It violates Liskov's Subtitution Principle. The point of polymorphism is that a caller should be able to treat a reference which actually refers to an instance of your derived class as if it refers to an instance of the base class.

考虑:

MyParentClass foo = GetParentClassFromSomewhere();
DoIt(null);

如果静态地确定它是有效的, 不,你不是要用一个空参数调用 DoIt !合同的静态分析的目的是,你可以确定调用,逻辑等在编译时的有效性...所以没有额外的限制可以在执行时添加,这是发生在这里由于多态性。

If that's statically determined to be valid, it's wrong for your derived class to hold up its hands and say "No! You're not meant to call DoIt with a null argument!" The aim of static analysis of contracts is that you can determine validity of calls, logic etc at compile-time... so no extra restrictions can be added at execution time, which is what happens here due to polymorphism.

派生类可以增加对它将要做什么的保证 - 它将确保什么 - 但是它不能对其重写方法的调用者发出任何更多的请求

A derived class can add guarantees about what it will do - what it will ensure - but it can't make any more demands from its callers for overridden methods.

这篇关于为什么不能在覆盖方法中添加Contract.Requires?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆