首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可以使用字符串值替换C#计算中的+或-运算符吗?

可以使用字符串值替换C#计算中的+或-运算符吗?
EN

Stack Overflow用户
提问于 2015-10-18 14:35:56
回答 2查看 89关注 0票数 0

我在operationComboBox.Text中包含了一个字符串,并且我知道该字符串要么是"+“,要么是"-”。然后,我可以使用以下代码对两个方程执行加减操作:

代码语言:javascript
复制
if ((operationComboBox.Text == "-"))
{
    equation3XCoeff = equations[index1].XCoeff - equations[index2].XCoeff;
    equation3YCoeff = equations[index1].YCoeff - equations[index2].YCoeff;
    equation3Answer = equations[index1].Answer - equations[index2].Answer;
}
else //if (operationComboBox.Text=="+")
{
    equation3XCoeff = equations[index1].XCoeff + equations[index2].XCoeff;
    equation3YCoeff = equations[index1].YCoeff + equations[index2].YCoeff;
    equation3Answer = equations[index1].Answer + equations[index2].Answer;
}

我的问题是,我是否可以去掉if语句,直接在要执行的和中使用字符串值,以便如何缩短我的代码?它可能不太重要,但我只是希望我的代码是简短的,这3次计算几乎重复,但符号。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-18 14:46:53

您不能直接使用它--它是一个字符串,不能用字符串代替操作符。但是根据文本,您可以初始化一些数值变量并在您的方程中使用它:

代码语言:javascript
复制
var coef = operationComboBox.Text == "-" ? -1 : 1;

equation3XCoeff = equations[index1].XCoeff + coef * equations[index2].XCoeff;
equation3YCoeff = equations[index1].YCoeff + coef * equations[index2].YCoeff;
equation3Answer = equations[index1].Answer + coef * equations[index2].Answer;
票数 4
EN

Stack Overflow用户

发布于 2015-10-18 14:47:48

我不认为您可以这样做,因为您在visual中编写的代码没有编译成原始类型的“string”。Visual将无法解释它,它只会看到您将一些随机的原始类型'string‘放在不知道的地方。你最好试一试,你会发现它不会编译。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33199194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档