以下代码片段的缩写形式是什么?
if (strValue == ""){
throw new Exception("Mandatory 'strValue' parameter empty");
}发布于 2011-04-19 04:34:49
它可能尽可能地短,不能去掉空格和大括号(并且在这个过程中牺牲了可读性)。
至于正确性。这样可能会更好:
.NET 4.0:
if (string.IsNullOrWhiteSpace(strValue)){
throw new ArgumentException("Mandatory 'strValue' parameter empty");
}.NET < 4.0:
if (string.IsNullOrEmpty(strValue)){
throw new ArgumentException("Mandatory 'strValue' parameter empty");
}还要注意的是,简单地抛出Exception是不好的做法-如果存在一个异常类,最好从BCL中选择一个合适的异常类,或者如果没有一个异常类,则选择一个自定义的异常类。
发布于 2011-04-19 04:35:44
if(strValue=="")throw new Exception("Mandatory 'strValue' parameter empty");您所能做的就是删除大括号和空格:)
发布于 2011-04-19 04:38:26
使用null检查,我认为您需要这样做,并使用ArgumentException:
ThrowIfNullOrEmpty(strValue, "strValue");
...
private void ThrowIfNullOrEmpty(string parameterValue, string parameterName)
{
if String.IsNullorEmpty(parameterValue)
{
throw new ArgumentException("Mandatory 'strValue' parameter empty",
parameterName);
}
}显然,只有当您多次执行此操作时才有用。
https://stackoverflow.com/questions/5708551
复制相似问题