我有以下方法,需要检查参数是否为空或null。
public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
{
_Where = " WHERE " + field + " " + operat + " @" + field + "1 " + andOr + " " + field2 + " " + operat2 + " @" + field2 + "2 ";
_Params.Add(field + "1", value);
_Params.Add(field2 + "2", value2);
return this;
}
我找到了字符串.IsNullOrWhiteSpace方法,但这需要写很多代码:
if (string.IsNullOrWhiteSpace(field))
throw new ArgumentException("field Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(operat))
throw new ArgumentException("operat Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("value Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(andOr))
throw new ArgumentException("andOr Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(field2))
throw new ArgumentException("field2 Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(operat2))
throw new ArgumentException("operat2 Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(value2))
throw new ArgumentException("value2 Cannot be null or be empty");
有没有缩短这个的方法?
另外,我尝试创建一个用于此任务的自定义方法,但它在自定义方法中抛出异常而不是Where()方法,这使得调试变得棘手。
ValidateParameterNotEmpty(string name, string value)
。这样可以将代码行数减少到三分之一。 - xanatosArgumentException
时不会显示任何内容。你是不是想使用nameof
? - Gediminas MasaitisWhere
方法接受param string[] args
呢?这会简化情况。 - tsul