C# 代码约定 userMessage 参数

标签 c# code-contracts

我在 C# 中使用代码契约,但我有点好奇我应该为 userMessage 参数输入什么。我将举一个简短的例子。

我的代码中有以下断言:

Contract.Assert(IsValidReferenceData(refData));

此消息永远不会显示给用户,但如果我和软件的其他开发人员/维护人员在异常中有一个英文消息描述会很好。

一开始我以为

Contract.Assert(IsValidReferenceData(refData), "Payment Reference is not valid");

但后来想到userMessage与boolean条件完全相反,于是改写为:

Contract.Assert(IsValidReferenceData(refData), "Payment Reference is valid");

因此消息和条件是相同的。然而,当人们看到异常报告并思考“等一下,如果引用有效,那么为什么会抛出异常?”时,这会让人们感到困惑。

最后,我想,为什么不做一个中立的声明,说什么必须是真的:

Contract.Assert(IsValidReferenceData(refData), "Payment Reference must be valid");

以上哪项是最佳实践?我想获得正确的消息,因为我计划在所有地方使用断言,以防止数据中出现不规则现象,为此我启用了运行时检查。

最佳答案

所以,有了 .Net 代码,我决定看看他们使用什么作为参数,结果是这样的:

"hashcode >= 0"
"Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized."
"Invalid MaxPrimeArrayLength"
"Missing case in GetRandomizedEqualityComparer!"
"We increment our current index by 8, so our buffer size must be a multiple of 8"
"key shouldn't be null!"
"Size is not zero"
"Didn't set Console::_out or _error appropriately!"
"Setting the foreground color before we've read the default foreground color!"

这里还有更多:http://pastebin.com/zPgU1ALe

基本上答案是:随便写什么,这条消息是为了让你快速调试,而不是为了你的 api 用户。

关于C# 代码约定 userMessage 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27016808/

相关文章:

c# - Rider 中对托管代码规则集的支持

c# - Xamarin-文件 :///android_asset

c# - 使用代码契约来定义不可变接口(interface)?

c# - 代码契约(Contract),forall 和自定义可枚举

c# - CodeContracts "Required"理解

c# - 调试时显示奇怪的对象成员

C# 运行时反射

c# - CodeContracts 无法证明简单的保证

c# - Contract.Requires 不阻止空引用警告(紫色波浪形)

c# - 连同数据一起序列化 XmlDoc 注释