c# - 不知道如何构建方法,C# WFA
问题描述
在为学校做项目时,我遇到了让我的方法发挥作用的问题。
以下是我需要创建的内容:
if (operator1 == "+")
{
//run method "calculate"
}
else if (operator1 == "-")
{
//run method "calculate"
}
而不是这个:
if (operator1 == "+")
{
decimal result = operand1 + operand2;
txtResult.Text = result.ToString();
}
else if (operator1 == "-")
{
decimal result = operand1 - operand2;
txtResult.Text = result.ToString();
}
我应该有以下内容:
private static Boolean Calculate(this string logic, int operand1, int operand2)
{
switch (logic)
{
case "-": return operand1 - operand2;
case "+": return operand1 + operand2;
case "/": return operand1 / operand2;
case "*": return operand1 * operand2;
default: throw new Exception("invalid logic");
}
}
这是我尝试过但不成功的概念,有什么建议吗?
作为参考,这些是我的项目的要求:
编写一个名为 Calculate 的私有方法,该方法执行请求的操作并返回一个十进制值。每个操作数需要两个十进制变量,运算符需要一个字符串变量(对 2 个值执行)。
解决方案
你的输入和返回类型是错误的,试试这个:
private static decimal Calculate(this string logic, decimal operand1, decimal operand2)
{
switch (logic)
{
case "-": return operand1 - operand2;
case "+": return operand1 + operand2;
case "/": return operand1 / operand2;
case "*": return operand1 * operand2;
default: throw new Exception("invalid logic");
}
}
另请注意,您正在使用只能在静态类中使用的扩展方法。要将其更改为常规方法,请this
从方法签名中删除。
推荐阅读
- android - 相对布局中的TextView和ListView
- powershell - 在一个命令中使用两个获取
- maven - 仅在打包/组装期间解决多模块 Maven 对分类器工件的依赖
- java - 无法为单元测试创建 Attribute 实例
- flutter - S.of(context) 返回 null
- java - 使用 AsyncHttpClient 的 REST 文件上传客户端的示例代码
- playframework-2.6 - 如何处理在单元测试中返回 Accumultor[ByteString,Result] 的动作
- r - mutate_if 仅应用于一列(看不到我的错误)
- ios - 没有读取 iCloud Drive 文件的权限
- python - 使用适用于 Python 的 Google Cloud 客户端库从存储桶下载文件