我张贴这个问题是为了找到一种更简单的方法来获得结果。
我们有一个检查NULL或string.empty的大型IF语句。如下所示:
if (string.IsNullOrEmpty(Empl.Name) || string.IsNullOrEmpty(Empl.last) ||
string.IsNullOrEmpty(Empl.init) || string.IsNullOrEmpty(Empl.cat1) ||
string.IsNullOrEmpty(Empl.history) || string.IsNullOrEmpty(Empl.cat2) ||
string.IsNullOrEmpty(Empl.year) || string.IsNullOrEmpty(Empl.month) ||
string.IsNullOrEmpty(Empl.retire) || string.IsNullOrEmpty(Empl.spouse) ||
string.IsNullOrEmpty(Empl.children) || string.IsNullOrEmpty(Empl.bday) ||
string.IsNullOrEmpty(Empl.hire)|| string.IsNullOrEmpty(Empl.death) ||
string.IsNullOrEmpty(Empl.JobName) || string.IsNullOrEmpty(Empl.More) ||
string.IsNullOrEmpty(Empl.AndMore))
{
//Display message. Something like "Error: Name and Month is missing"
return;
}到目前为止,我找到的任何解决方案都很耗时,而且需要编写更多的代码。
有没有办法知道哪个值是string.IsNullOrEmpty,而不需要对IF语句做太多修改?更糟糕的是,我可以单独检查每一条语句,但我不希望这样做。
谢谢。
发布于 2016-06-09 03:23:21
不,没有“魔术”函数可以告诉你OR语句中的一系列表达式中的哪一个是真的。此外,由于您使用的是短路版本,因此语句将在第一个true条件之后返回true,因此不会对其余表达式求值。
但是,您可以这样做:
bool[] checks = {
string.IsNullOrEmpty(Empl.Name) , string.IsNullOrEmpty(Empl.last) ,
string.IsNullOrEmpty(Empl.init) , string.IsNullOrEmpty(Empl.cat1) ,
string.IsNullOrEmpty(Empl.history) , string.IsNullOrEmpty(Empl.cat2) ,
string.IsNullOrEmpty(Empl.year) , string.IsNullOrEmpty(Empl.month) ,
string.IsNullOrEmpty(Empl.retire) , string.IsNullOrEmpty(Empl.spouse) ,
string.IsNullOrEmpty(Empl.children) , string.IsNullOrEmpty(Empl.bday) ,
string.IsNullOrEmpty(Empl.hire) , string.IsNullOrEmpty(Empl.death) ,
string.IsNullOrEmpty(Empl.JobName) , string.IsNullOrEmpty(Empl.More) ,
string.IsNullOrEmpty(Empl.AndMore)
};
if(checks.Any())
{
//Display message. Something like "Error: Name and Month is missing"
return;
}现在,checks变量保存了每个表达式的结果。
发布于 2016-06-09 03:32:54
我发现这是使用ModelState.isValid的一种更优雅的方式。
一些参考:What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?
对于您的模型,可以添加以下注释:
[Required(AllowEmptyStrings= false)]
public string Boo { get; set; }在进行验证时,请尝试:
if (!ModelState.IsValid)
{
//Display message. Something like "Error: Name and Month is missing"
return;
}发布于 2016-06-09 03:17:11
是的,编写自己的字符串扩展方法来执行相同的检查,但也接受列表并将字段名添加到列表中。在if之前声明字符串列表,您就会得到一个注释所在的有问题字段的列表。
这可以通过一些反射来改进,以自动获得名称,并可能进行一些优化,但它是在正确的轨道上。
请记住,第一个违反if语句的条件将导致它失败,因此您将得到一个不完整的列表(包含一个项目),除非您的if以不同的方式构造。
public static class StringExtensions
{
public static bool CheckIsNullOrEmptyAndListIt(this string field, string fieldName, List<string> naughties)
{
var result = String.IsNullOrEmpty(field);
if (result == true)
{
naughties.Add(fieldName);
}
return result;
}
}
}https://stackoverflow.com/questions/37711004
复制相似问题