似乎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];
}
}
有什么技巧可以避免吗?
答案 0 :(得分:1)
合同超载userMessage
,例如Requires(bool condition, string userMessage),要求userMessage
消息为文字或静态(例如static readonly
)或const
,根据错误消息。
由于用户消息适合您,因此开发人员,而不是用户为什么不只是将其设为通用:
String.Format("There is no row with this index in the table");
关于将什么放入(IMO名称不当)userMessage parameter here
的讨论更多