CodeContract problem with ensures

对着背影说爱祢 提交于 2020-02-06 04:12:31

问题


I got the following code:

    protected virtual string FormatException(Exception exception, int intendation)
    {
        Contract.Requires(intendation >= 0);
        Contract.Requires<ArgumentNullException>(exception != null);
        Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));

        var msg = exception.ToString().Replace("\r\n", "\r\n".PadRight(intendation, '\t'));
        string text = string.Format("\r\n******* EXCEPTION ********\r\n\t{0}", msg);
        return text;
    }

It gives me

Warning 19 CodeContracts: ensures unproven: !String.IsNullOrEmpty(Contract.Result())

Why?


回答1:


I don't know if the String.Format() function has any contracts but it could only promise that the result != null, an empty string is a valid result.

I checked: String.Format() only ensures result != null

You can simply fix it by inserting an Assume() :

Contract.Assume(!String.IsNullOrEmpty(text));
return text;

But I would seriously reconsider making result is not empty part of your contract here. Does it really matter to the callers?



来源:https://stackoverflow.com/questions/6889245/codecontract-problem-with-ensures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!