我有下面的方法,我需要检查参数是否为空或 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;
}
我找到了 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() 方法中抛出异常,这使得调试变得棘手。
最佳答案
您可以一个一个地检查值或创建中间函数来执行此操作。
或者,我的建议是:您可以将所有输入放在一个数组中,然后使用 LINQ Any 一次检查所有输入:
public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
{
string[] inputs = {field, operat, value, andOr, field2, operat2, value2}
if (inputs.Any(x => string.IsNullOrWhiteSpace(x))){
//throw exception
}
//continue with your method, all inputs are OK
}
关于c# - 如何检查多个参数的 null 或空字符串? - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35816997/