代码契约:封装 require 方法时格式错误,无法使用 String.Format
Code Contract: malformed when incapsulate require method and unable to use String.Format
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];
}
}
有什么技巧可以避免吗?
对于point #1 have a look here
采用 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
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];
}
}
有什么技巧可以避免吗?
对于point #1 have a look here
采用 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