如何在C#中检查多个参数是否为null或空字符串?

3

我有以下方法,需要检查参数是否为空或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)。这样可以将代码行数减少到三分之一。 - xanatos
你需要进行的验证以防止 SQL 注入将需要更多的工作,因此我建议将其作为第二优先级。 - Crowcoder
2
如果字段为 null 或空,则抛出 ArgumentException 时不会显示任何内容。你是不是想使用 nameof - Gediminas Masaitis
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Chris
@GediminasMasaitis 是的,抱歉那是个错误。虽然我不认为我可以使用 nameof(),因为我没有使用 c#6。我会修改成我现在拥有的。 - Chris
为什么不让你的 Where 方法接受 param string[] args 呢?这会简化情况。 - tsul
5个回答

6
你可以逐个检查数值,也可以创建中间函数来完成。
另外,我的建议是:你可以将所有的输入放入一个数组中,然后使用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
}

非常有趣的方法。wp - RAMM-HDR

1
我可以建议的是这个:
private string _nullChecker(string _value){
   if (string.IsNullOrWhiteSpace(_value))
            throw new ArgumentException(_value + "Cannot be null or be   empty");
   return _value;
}

然后,在你的Where语句中。
_Where = " WHERE " + _nullChecker(field) + " " + __nullChecker(operat) + " @" + _nullChecker(field) + "1 " + _nullChecker(andOr) + " " + _nullChecker(field2) + " " + _nullChecker(operat2) + " @" + _nullChecker(field2) + "2 ";

不过我没用实际代码检查过。 :) 希望这有所帮助。


1
或者它可能是一个扩展方法。 - tsul

0

首先,您可以使用简单的库来进行参数验证。看看这个名为Argument Validator的库,它具有方便的函数,可以将您的整体代码减少一半。

下面是一个使用参数验证程序库的示例:

public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
{
    var inputs = new string[] {field, operat, value, andOr, field2, operat2, value2};
    foreach(var input in inputs)
    {
        Throw.IfNullOrEmpty(input, nameof(input)));
    }
}    

0

我想我找到了你正在做的“分支”。下面的代码较少,错误是在函数内抛出的。

Adam Storr有一篇很棒的文章关于参数检查这里

对于懒惰的人,您会发现使用扩展方法的用法,允许在try/catch中一行内检查参数。

它允许独立检查所有参数,并提供自定义反馈。

public returnType MyFunction(string arg1, string arg2, int arg3)
{
    try
    {
        // Check that the arguments are not null or empty
        _ = arg1.Valid() ?? throw new ArgumentNullException("Argument 1 not valid");
        _ = arg2.Valid() ?? throw new ArgumentNullException("The argument 2 must be provided");
        _ = arg3.Valid() ?? throw new ArgumentNullException("I need arg3 to work");
    }
    catch(ArgumentNullException)
    {
    //Treat the error
    }

而 .Valid() 方法的实现则可以在任何您想要的地方进行(在这种情况下存储在 TypeExtension 文件中):

 public static class TypeExtensions
    {
        /// <summary>
        /// String method extension that return null if the string is null or empty.<br/>
        /// Otherwise return the value itself
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object Valid(this string value)
        {
            return (!string.IsNullOrWhiteSpace(value)) ? value : null;
        }

        /// <summary>
        /// int method extension that return null if the int is null or 0 <br/>
        /// Otherwise return the value itself
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object Valid(this int? value)
        {
            if (value is null or 0)
                return null;
            else
                return value;
        }
    }

因此,Valid()方法的inherit参数是由其类型确定的。

"null-coalescing operator" (??)意味着"如果值为null,则给出下一个值"

舍弃符号"_"表示无论返回什么都不会存储在内存中。

因此,通过两者的关联,您可以检查参数,如果检查返回null,请抛出异常。

我同意这对于扭曲的思维来说可能很难理解,但是目前我没有找到更好的方法。也许使用装饰器?

希望这能有所帮助!


0
你可以这样做:
int? GetLength(string s) {
    return s == "" ? -1 : s?.Length;
}

// s1, s2 and so on are your parameters
int? lengthSum = GetLength(s1) + GetLength(s2); // and so on
int wholeLength = (s1 + s2).Length; // and so on
if(lengthSum == wholeLength) {
    // No parameter is null or empty
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接