1

DevLab 的 CodeContract 似乎是一个不错的工具,但我在代码中有两个错误:

public class SomeClass
{
   private DataTable _dataTable

   // I don't want to write the same condition more then ones, so incapsulate it
   private void CheckRowIndex(int rowIndex)
   {
      //Error1 in next line: User message to contract call can only be string literal, or a static
      // field, or static property that is at least internally visible.    
      Contract.Requires<IndexOutOfRangeException>(_dataTable.Rows.Count >= rowIndex + 1,
        String.Format("There is no row with index {0} in table.", rowIndex));
   }

   public object GetObject(int rowIndex, int colIndex)
   {
     // Error2 in next line: malformed contract
     CheckRowIndex();
     return _dataTable.Rows[rowIndex][colIndex];
   }
   public object GetObject(int rowIndex, string colName)
   {
     CheckRowIndex();
     return _dataTable.Rows[rowIndex][colName];
   }
}

有什么技巧可以避免吗?

4

1 回答 1

1

对于第 1 点,请看这里

采用Requires(bool condition, string userMessage)userMessage之类的合同重载要求消息是文字或静态(例如),或,根据错误消息。userMessagestatic readonlyconst

既然用户消息是给你的,开发者,而不是给用户的,为什么不让它通用:

String.Format("There is no row with this index in the table");

这里有更多关于在 (IMO badly named) userMessage 参数中放入什么的讨论

于 2015-01-05T09:38:10.693 回答