我有一个像文件一样的xml
<Config>
<Allowed></Allowed>
</Config>
Run Code Online (Sandbox Code Playgroud)
Allowed标记如下所示:
string isAllowed = (string)xml.Root
.Element("Config")
.Elements("Allowed")
.SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)
isAllowed应该采用默认值true
这是执行此操作的代码:
if (isAllowed == null)
{
DoSomething();
return true;
}
if (isAllowed.Length == 0)
{
DoSomething();
return true;
}
if (isAllowed.Length != 0)
{
if (isAllowed.ToUpper() != "FALSE" && isAllowed.ToUpper() != "NO")
{
DoSomething();
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
必须有更好的方法来做到这一点?
if (isAllowed == null)
{
DoSomething();
return true;
}
if (isAllowed.Length == 0)
{
DoSomething();
return true;
}
Run Code Online (Sandbox Code Playgroud)
可以替换为:
if (string.IsNullOrEmpty(isAllowed)
{
DoSomething();
Return true;
}
Run Code Online (Sandbox Code Playgroud)
但实际上,根据您的标准,我认为string.IsNullOrWhiteSpace(isAllowed)更合适,因为如果标签的内容为"空",它将返回true.
此外,您第二次不需要以下条件,因为如果条件满足,则第一次返回函数将返回(短路评估).这意味着您当前在第二个If块中的语句永远不会被执行.
if (isAllowed.Length != 0)
Run Code Online (Sandbox Code Playgroud)
我的第一个让这个更干净的本能是采用与Jon在答案中所做的相同的方法,重复它没有任何优势.但是,我确实认为这是另一个好的设计,因为你应该引入更多更清洁的条件:
private static bool Validate(string isAllowed)
{
var defaultTrueConditions = new[] {"true", "false", "yes", "no"};
if (string.IsNullOrWhiteSpace(isAllowed) ||
defaultTrueConditions.Contains(isAllowed, StringComparer.OrdinalIgnoreCase))
{
DoSomething();
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |