首页 > 解决方案 > 不知道如何构建方法,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 个值执行)。

标签: c#.net

解决方案


你的输入和返回类型是错误的,试试这个:

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从方法签名中删除。


推荐阅读