检查方法中的多个字符串参数值是否为空

时间:2014-05-18 19:51:26

标签: c# asp.net web-config

如果我有类似于

的C#方法
public void MyMethod(object myObject, string s1, string s2, string s3, ...)
{ ... }

我需要对字符串进行值检查(如果是!string.IsNullOrEmpty( var )),而不是遍历每个变量,因为有很多if检查,是有一种更通用的方法可以实现这个目标吗?

我希望使用ParameterInfo,直到我发现你无法检索参数的值。我的参数将是""或者具有数字(作为字符串)或true / false(作为字符串)的值 - 这些是进入web.config,因此是字符串。方法变量的名称是进入web.config的参数名称。我阻止将具有null / empty值的参数写入web.config,因此检查IsNullOrEmpty。

现在我对每个方法参数的内容如下所示,只是为了让您了解格式。

string name, value;
if (!string.IsNullOrEmpty(s1))
{
 name = "s1";
 value = s1;
 /* do stuff */
}
if (!string.IsNullOrEmpty(s2))
{
 name = "s2";
 value = s2;
 /* do stuff */
}
/* too many of these */

1 个答案:

答案 0 :(得分:1)

我认为传递而不是string1,string2等会更好..类似于字符串数组(string[])。

通过这种方式,您将能够传递2个参数或10000,并且您不需要检查,因为在您的数组中,如果需要,您将不会包含空值;)

编辑:字典获胜

public void MyMethod(object myObject, Dictionary<int, string> yourParams)
{ ... }
相关问题