代码之家  ›  专栏  ›  技术社区  ›  MatthewMartin muthu

“合同不能在试块”是什么意思?

  •  6
  • MatthewMartin muthu  · 技术社区  · 14 年前

    我正在使用3.5的微软代码合同库

    public object RetrieveById(int Id)
    {    
        //stuff happens...
        Contract.Ensures(newObject != null, "object must not be null");
        return newProject;
        //No error message if I move the Contract.Ensures to here
        //But it isn't asserting/throwing a contract exception here either           
    }
    

    更新:

    在你的帮助下我想出来了:

    • 移到顶部
    • 对照合同检查结果

      Contract.executes(Contract.Result()!=null,“对象不能为null”);

    3 回复  |  直到 14 年前
        1
  •  6
  •   Tim Cooper    13 年前

    http://msdn.microsoft.com/en-us/library/dd412865.aspx

    上面写着:

    方法或属性的开头, 在任何其他代码之前。

        2
  •  3
  •   Hans Passant    14 年前

    很简单:Contract类通过抛出一个异常来表示违反了合同。把它放在一个try块中会破坏目的,你可能会发现异常。

        3
  •  2
  •   KP.    14 年前

    这里有一个类似的解决方案:

    http://social.msdn.microsoft.com/Forums/en/codecontracts/thread/43f467f1-14b7-4e56-8030-50f842b7ba68

    Contract.Ensures 声明。 必须位于方法中任何其他代码之前,因此:

    public object RetrieveById(int Id)
    {    
        //first line of method:
        Contract.Ensures(newObject != null, "object must not be null");
    
        //stuff happens...
    
        return newProject;        
    }