2011-04-18 53 views
1

与以下代码片段相当的速记是什么?等效缩写

if (strValue == ""){ 
    throw new Exception("Mandatory 'strValue' parameter empty"); 
} 
+4

这已经很短了。任何更短的内容都可能导致无法阅读。 – 2011-04-18 20:34:25

回答

9

它可能尽可能短,除非删除空格和大括号(并牺牲了可读性)。

至于正确性...这可能会更好:

.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中选择适当的异常类(如果存在的话)或自定义的类(如果不存在的话)会更好。 (谢谢@djacobson)

+0

如果你抛出一个'ArgumentException'而不是一个'Exception',它可能会*更好*。 – 2011-04-21 19:57:07

+0

@djacobson - 公平点。答复修正。 – Oded 2011-04-21 20:01:40

3

您可以使用代码合同。

您也可以使用string.IsNullOrWhitespace()

Contract.Requires(string.IsNullOrEmpty(strValue), "** fancy localized message here ***"); 
+0

“更短”的原因是您可以有条件地将其从发布版本中删除,并将检查保留在已检查的版本中。 – GregC 2011-04-18 20:48:10

5
if(strValue=="")throw new Exception("Mandatory 'strValue' parameter empty"); 

所有你能做的就是去掉括号和空格:)

+0

我想你是对的! (如果你真的想要相当):) – 2011-04-18 20:37:02

1

它已经短。而不是做strValue ==“”,我会做String.Empty或String.NullOrEmpty,我不记得哪一个可用于.NET。

1

不会变得更短,但如果需要更少的行:

if (String.IsNullOrWhitespace(strValue)) throw new Exception("Mandatory 'strValue' parameter empty"); 
4

随着空校验,我想你想和使用的ArgumentException:

ThrowIfNullOrEmpty(strValue, "strValue"); 

... 

private void ThrowIfNullOrEmpty(string parameterValue, string parameterName) 
{ 
    if String.IsNullorEmpty(parameterValue) 
    { 
     throw new ArgumentException("Mandatory 'strValue' parameter empty", 
            parameterName); 
    } 
} 

显然只有当你在做多几次这样更加有用。

+0

+1:伟大的重用。 – 2011-04-18 20:39:14

+0

会做出很好的扩展方法,可能会将parameterValue参数放入表达式中并将名称拉回来以消除对parameterName参数的需要。 (你已经抛出了一个异常,这是多少开销?:)) – asawyer 2011-04-18 20:45:29

+0

@asawyer:嗯。在这种情况下,扩展方法感觉不对。我正在采取的行动是在方法的上下文中 - 现在,如果我可以对*方法*本身做一个扩展方法...我猜,它正在接近代码合同。 – 2011-04-18 20:47:43

0

假设你正在尝试写更多的防守代码,你可以使用Trace.Assert

Trace.Assert(strValue != "", "Mandatory 'strValue' parameter is not empty"); 

或者你可以使用Fluent Validation库封装更复杂的验证。

1

你几乎就像你可以得到的一样短。我建议使用IsNullOrEmpty字符串函数来检查一个空字符串。另外,在您的异常处理中可能更具体,并抛出ArgumentException

if (String.IsNullOrEmpty(strValue)) { throw new ArgumentException("strValue must not be null or empty") }; 
+0

+1,用于提及ArgumentException。 – juharr 2011-04-18 21:14:12