我想知道这些方法之间是否有任何区别
public bool GetCondition(string s1, string s2)
{
if (s1.StartsWith('a'))
{
return false;
}
if (s2.StartsWith('c'))
{
return false;
}
if (s1.StartsWith('b') && s2.StartsWith('d'))
{
return false;
}
return true;
}
和
public bool GetCondition(string s1, string s2)
{
if (s1.StartsWith('a'))
{
return false;
}
else if (s2.StartsWith('c'))
{
return false;
}
else if (s1.StartsWith('b') && s2.StartsWith('d'))
{
return false;
}
return true;
}
它们是否相同或是否有不同的行为?如果不是,那么更好的写作方式是什么?
答案 0 :(得分:2)
在你的情况下没有,没有区别,但通常有一个
如果您使用
if(...){
}
if(...){
}
if(...){
}
即使其中一个是正确的,也会经历每一次,
但如果您使用:
if(...){
}
else if(...){
}
else if(...){
}
如果为真则将忽略其他的完全
答案 1 :(得分:0)
在这种情况下,它们是相等的,因为当条件为真时退出。
答案 2 :(得分:0)
是的,有平等的。
你可以这样写:
public bool GetCondition(string s1, string s2)
{
if (s1.StartsWith('a') || s2.StartsWith('c') || (s1.StartsWith('b') && s2.StartsWith('d')))
{
return false;
}
return true;
}
但是,你提出的两个例子也很好。选择更适合您的接缝,以便您理解。