"Contract section within try block" 上下文连接错误

"Contract section within try block" error for context connection

我已经写了这段代码及其合同:

[Pure]
public string getLevelName()
{
    using (var c = new myContext())
    {
        Contract.Ensures(Contract.Result<string>() == c.Level.FirstOrDefault(i => i.levelId == this.levelId).name);
        return c.Level.FirstOrDefault(i => i.levelId == this.levelId).name;
    }

}

但我收到合同错误:

Contract section within try block.

如何避免这种方法合同的错误?

您必须将所有 Contract.Ensures 调用放在方法的开头。 using 语句是 shorthand 用于 try finally 块(编译器会为您推断)。

您的代码:

using (var c = new myContext())
{
    Contract.Ensures(Contract.Result<string>() == c.Level.FirstOrDefault(i => i.levelId == this.levelId).name);
    return c.Level.FirstOrDefault(i => i.levelId == this.levelId).name;
}

变成:

var c = new myContext();
try{
    Contract.Ensures(Contract.Result<string>() == c.Level.FirstOrDefault(i => i.levelId == this.levelId).name);
}
finally
{
    if (c != null)
        ((IDisposable)c).Dispose();
}

所以本质上你是将 Contract.Ensures 调用放入 try 块中(就像错误告诉你的那样)。请参阅这篇 msdn 文章 http://msdn.microsoft.com/en-us/library/dd412865.aspx 特别是:

This method call must be at the beginning of a method or property, before any other code.

文档says

This method call must be at the beginning of a method or property, before any other code.

在你的样本中

using (var c = new myContext())

将被编译器转换为

try 
{
  c = new myContext();
  Contract.Ensures ...
}
finally
{
   c.Dispose();
}

为避免这种情况,请使用另一个私有方法并在那里传递您的上下文

尝试调用另一个方法,

public string getLevelName()
{
    using (var c = new myContext())
    {
       return getLevelNameFrom(c);
    }

}

public string getLevelNameFrom(MyContext c)
{
        Contract.Ensures(Contract.Result<string>() == c.Level.FirstOrDefault(i => i.levelId == this.levelId).name);
        return c.Level.FirstOrDefault(i => i.levelId == this.levelId).name;
}