如何检查许多参数的null或空字符串?- C# [英] How do I check for null or empty string for many arguments? - C#

查看:74
本文介绍了如何检查许多参数的null或空字符串?- C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法,需要检查参数是否为空或为null.

I have the below method, which I need to check for whether the arguments are empty or 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方法,但是这需要很多代码:

I have found the string.IsNullOrWhiteSpace method however this would require this much code:

                   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");

有什么方法可以缩短这个时间吗?

Is there any way of shortening this?

此外,我尝试为此任务创建一个自定义方法,但是它在自定义方法中引发了异常,而不是Where()方法,这使得调试起来很棘手.

Also, I have tried creating a custom method for this task, however it throws an exception in the custom method instead of the Where() method which makes it tricky to debug.

推荐答案

您可以一一检查值,也可以创建中间函数来做到这一点.

You could check the value one by one or creating intermediate function to do that.

或者,我的建议是:您可以将所有输入放在一个数组中,然后使用LINQ Any一次检查所有输入:

Alternatively, my suggestion is: you could put all the inputs in an array and use LINQ Any to check all of them at once:

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
}

这篇关于如何检查许多参数的null或空字符串?- C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆