我有下面的方法,我需要检查参数是否为空或空。如何为多个参数检查空字符串或空字符串? - C#
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;
}
我已经找到了string.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(字符串名称,字符串值)'。您将减少行数到1/3 – xanatos
您需要做的预防SQL注入的验证将会花费更多的工作量,所以我会优先考虑。 – Crowcoder
如果该字段为空或空,那么在以您的方式抛出'ArgumentException'时不会出现任何内容。你的意思是使用['nameof'](https://msdn.microsoft.com/en-us/library/dn986596.aspx)? –