C#。这是一个有效的条件语句吗?
我有两种方法,A
和 B
。只有在两种方法成功后,我才必须插入数据库。那么这是 C# 中有效的条件语句吗?
if (A() && B())
{
//insert into db
}
执行方法A
后,我必须执行B
。如果两者都成功,我必须进行插入。
I have two methods, A
and B
. Only after the success of two the methods I have to insert into a database. So is this a valid conditional Statement in C#?
if (A() && B())
{
//insert into db
}
After the execution of method A
I have to execute B
. If both are successful I have to do the insert.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,它是有效的。但请注意,只有当
A()
返回 true 时,B
才会执行。Yes it is valid. But note that
B
will only execute ifA()
returns true.这称为短路评估
条件将按照出现的顺序进行评估,并且只有当他们的测试仍然相关时。也就是说,如果 A() 失败,就没有理由测试 B()。
This is called short-circuit evaluation
The conditions will be evaluated in the order of appearance, and only if their testing is still relevant. That is, if A() fails, there is no reason to test B().
正如他们所说,如果 A() 返回 false,则 B() 不会执行。
如果您希望执行这两个函数,我建议如下:
As they say B() is not executing if A() returns false.
If you want both functions to be executed I recommend something like:
其他人已经回答了您的问题,但只是为了澄清一下,因为这里有一些稍微误导性的帖子...
&&
运算符短路if (false && Foo()) // Foo() 未运行
&
运算符不短路if (false & ; Foo()) // Foo() is run
如果您想确保您的函数具有副作用,请使用后者。
Your question has already been answered by others, but just to clarify as there are a couple of slightly misleading posts on here...
The
&&
operator is short-circuitingif (false && Foo()) // Foo() is not run
The
&
operator is not short-circuitingif (false & Foo()) // Foo() is run
Use the latter if your functions have side effects which you want to ensure.
在两个函数中设置 fa=1 fd=1 。
然后检查
if(fa==fb==1)
{
//做
}
set fa=1 fd=1 inside both function.
Then check
if(fa==fb==1)
{
//do
}
应该是
这将注意这两个函数都被执行。
It should be
This will take care that both the functions are getting executed.