在C#中返回函数值

时间:2014-10-14 23:35:34

标签: c#

我正在开发一个c#程序,它使用姓名,工作小时数,小时费率和扣减代码输入来计算总薪资,税金,扣除额和净工资。我遇到一个特定部分的问题。我无法通过我的“GrossPay”功能将总薪酬作为在我的文本框中显示的金额返回。该函数将工作小时数和小时费用作为参数并将它们相乘,将结果分配给总工资,然后将其返回。我对C#语法不是很了解所以我一直在使用互联网作为资源来尝试编写这段代码。这是该程序到目前为止的代码(不完整)。

 private void btnCalculate_Click(object sender, EventArgs e)
    {
        string employeeName = txtEmployeeName.Text;
        decimal hoursWorked = Decimal.Parse(txtHoursWorked.Text);
        decimal hourlyRate = Decimal.Parse(txtHourlyRate.Text);
        int deductionCode = Int32.Parse(txtDeductionCode.Text);
        GrossPay();
    }

    private void GrossPay(decimal hoursWorked, decimal hourlyRate)
    {
        decimal grossPay = hoursWorked * hourlyRate;    
        grossPay = Decimal.Parse(txtGrossPay.Text);
    }

1 个答案:

答案 0 :(得分:3)

您将返回类型设置为void,这意味着它在完成时不会返回任何内容。为了返回某些内容,您必须声明要返回的类型。然后在您的功能代码到达“结束”之前,您必须返回一些东西(或抛出异常)。

在这种情况下,让我们将返回类型设置为decimal并返回grossPay变量,其类型为decimal。我们也不需要从TextBox中解析它,因为你通过函数参数传递它。

private decimal GrossPay(decimal hoursWorked, decimal hourlyRate)
{
    decimal grossPay = hoursWorked * hourlyRate;    
    return grossPay;
}

我们可以缩短它,因为不需要grossPay变量。

private decimal GrossPay(decimal hoursWorked, decimal hourlyRate)
{
    return hoursWorked * hourlyRate;    
}

由于此函数似乎不依赖于任何外部信息,因此将它设置为静态函数可能会很好,因此在调用GrossPay()之前我们不必拥有该类的实例。功能

private static decimal GrossPay(decimal hoursWorked, decimal hourlyRate)
{
    return hoursWorked * hourlyRate;    
}

将其设为静态允许您像这样调用它:

decimal grossPay = MyCalculationUtilities.GrossPay(hoursWorked, hourlyRate);

而不是:

MyCalculationUtilities calculator = new MyCalculationUtilities();
decimalgrossPay = calculator.GrossPay(hoursWorked, hourlyRate);

最后一个建议,我建议将其从GrossPay更改为CalculateGrossPay,因为它更能描述函数的实际功能。