Pet*_*ter 2 .net c# if-statement exception
我有一个关于何时使用Exception或If/Else语句的问题.在我的情况下,我想检查DocumentNode是否是TestNode.当它是TestNode时,我想获得节点.
我在下面写了两个可能的解决方案.第一个解决方案认为它是TestNode,否则它会产生异常.第二个解决方案检查它是否是TestNode,然后它执行大致相同的函数来获取节点.谁能告诉我什么是最好的解决方案?或者有更好的解决方案吗?谢谢,彼得.
*对不起,我的英语不好..
private DocumentNode GetTestNode(IEnumerable<DocumentNode> nodes)
{
foreach (DocumentNode node in nodes)
{
if (node.GetValueProperty().ToString() == "TestValue")
{
return node;
}
}
throw new TestNodeNotFoundException("This is not a TestNode");
}
OR:
private DocumentNode IsTestNode(IEnumerable<DocumentNode> nodes)
{
foreach (DocumentNode node in nodes)
{
if (node.GetValueProperty().ToString() == "TestValue")
{
return true;
}
}
return false;
}
private DocumentNode GetTestNode(IEnumerable<DocumentNode> nodes)
{
foreach (DocumentNode node in nodes)
{
if (node.GetValueProperty().ToString() == "TestValue")
{
return node;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果可以,更好的解决方案是使用LINQ.如果您想要例外,您可以使用:
var node = nodes.Where(n => node.GetPropertyValue().ToString() == "TestValue")
.First();
Run Code Online (Sandbox Code Playgroud)
(Single如果应该只有一个这样的节点,也可以使用.)
如果您不想要例外,请FirstOrDefault改用:
var node = nodes.Where(n => node.GetPropertyValue().ToString() == "TestValue")
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
然后,node如果没有测试值的节点将是无效的.
要测试是否存在测试节点,请使用 Any
var isTest = nodes.Where(n => node.GetPropertyValue().ToString() == "TestValue")
.Any();
Run Code Online (Sandbox Code Playgroud)
(你的最终方法目前不会编译,因为它可以在不返回的情况下到达终点.)
哪个合适取决于你想要做什么.如果缺少测试节点表明存在错误,则抛出异常是合适的.如果没有,使用null信号表示非常合理,或者您可以使用TryXXX模式显式返回bool值,同时将找到的节点(如果有)保存在out参数中.