c# - C# get Result from IF Statement
问题描述
I have a simple code like:
public IActionResult TestingSample(int A, int B)
{
if (A > B && B != 0)
{
int corr = 2 + A * B;
string rescorr = corr.ToString();
}
else
{
int wron = 2 * A + B;
string reswron = wron.ToString();
}
}
From the code above, I want to add a result with: rescorr + reswron
. So it becomes string result. How can I write the return value with string like that?
Really appreciated.
Thank you.
解决方案
You should probably start by moving your string variables out of the if blocks
And then return the concatenated string.
public IActionResult TestingSample(int A, int B)
{
string rescorr = string.Empty;
string reswron = string.Empty;
if (A > B && B != 0)
{
int corr = 2 + A * B;
rescorr = corr.ToString();
}
else
{
int wron = 2 * A + B;
reswron = wron.ToString();
}
return rescorr + reswron;
}
Then you realise that only 1 of these will ever get set so we change the string assignments in to individual returns. We get get rid of the variables and the else block because that's now redundant too.
public IActionResult TestingSample(int A, int B)
{
if (A > B && B != 0)
{
int corr = 2 + A * B;
return corr.ToString();
}
int wron = 2 * A + B;
return wron.ToString();
}
推荐阅读
- c - 有人可以解释 C 中gets() 的返回值吗?
- html - 尝试在填充框中添加浮动图像和描述
- swift - 未找到 WatchKit 接口控制器
- php - 如何在php中使用特定键爆炸数组
- python - sklearn.metrics.log_loss 是否支持多标签设置?
- python - 如何在 tkinter 模块中动态显示数据-Python
- java - java中不可变的dto如何序列化/反序列化?
- python - 拆分 url 并在列中从该 URl 获取值
- python - 使用 TimeDistributed Conv2D 层包装器
- javascript - MongoDB > 我可以在查询中使用实例数据 upsertMany