[英]if return statement in c#
I am overriding a virtual method and I need to return a value depending on a bool expression. 我覆盖了一个虚方法,我需要根据布尔表达式返回一个值。
public override float Q()
{
return (float)Math.Sqrt(2 * A* B / C);
}
I need to return a local member (call it D) for Q() if the calculated value shown above is less than D. I tried using regular if statements, but it won't return a value unless it's returned outside the if statement. 如果上面显示的计算值小于D,我需要为Q()返回一个本地成员(称为D)。我尝试使用常规的if语句,但是除非在if语句之外返回,否则它不会返回任何值。 Any help would be appreciated.
任何帮助,将不胜感激。
How about skipping the if
altogether: 如何完全跳过
if
:
return Math.Max(D, Math.Sqrt (2*A*B/C));
or with ternary operator 或带有三元运算符
return Math.Sqrt (2*A*B/C) < D ? D : Math.Sqrt (2*A*B/C); // too verbose but you get the idea
i would think this would work 我认为这会工作
public override float Q(){
var returnValue = (float)Math.Sqrt(2 * A * B / C);
if (returnValue < D){
return D;
}
return returnValue;
}
EDIT : 编辑:
or you can clean it up to this 或者你可以清理它
public override float Q(){
var returnValue = (float)Math.Sqrt(2 * A * B / C);
return returnValue < D ? D : returnValue;
}
public override float Q()
{
var result = (float)Math.Sqrt(2 * A* B / C);
return result < D ? D : result;
}
Unless this is a trick question, since D
is local to the class, the code should look like this: 除非这是一个棘手的问题,否则由于
D
在类中是本地的,因此代码应如下所示:
public override float Q()
{
var result = (float)Math.Sqrt(2 * A* B / C);
return result < D ? D : result;
}
but note that D
needs to be a float
or cast to a float
on the return if it's not. 但请注意,
D
必须为float
否则必须为返回值的float
。 Further, if D
isn't a float
you may want to just do something like this because its type may not be implicitly convertable: 此外,如果
D
不是float
您可能只想执行以下操作,因为其类型可能无法隐式转换:
public override float Q()
{
var d = (float)D;
var result = (float)Math.Sqrt(2 * A* B / C);
return result < d ? d : result;
}
Something like this: 像这样:
public override float Q(){
var r = (float)Math.Sqrt(2 * A * B / C);
if (r < D){
r = D;
}
return r;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.