0

我似乎无法弄清楚我们的问题是什么。pph 和两者在不同的重载中都等于不同的值。我不确定我做错了什么。我看不出这些值是如何相同的。

public class Pay
{
    public double ComputePay(double h,double pph,double with)
    {
        double net = 0;

        try
        {
            double gross = h * pph;
            net = gross - with;
        }
        catch (FormatException)
        {
            Console.WriteLine("Hour's cannot be less than zero");
        }

        return net;      
    }

    public double ComputePay(double h, double pph, double with = 0.15)
    {
        double net = 0;

        try
        {
            double gross = h * pph;
            net = gross - with;
        }
        catch (FormatException)
        {
            Console.WriteLine("Hour's cannot be less than zero");
        }

        return net;
    }

    public double ComputePay(double h, double pph = 5.85, double with = 0.15)
    {
        double net = 0;

        try
        {
            double gross = h * pph;
            net = gross - with;
        }
        catch (FormatException)
        {
            Console.WriteLine("Hour's cannot be less than zero");
        }

        return net;
    }
}
4

4 回答 4

3

我不确定我做错了什么。

你有三个方法,它们都有三个double参数:

public double ComputePay(double h,double pph,double with)
public double ComputePay(double h, double pph, double with = 0.15)
public double ComputePay(double h, double pph = 5.85, double with = 0.15)

某些方法声明中的某些参数是可选的这一事实与此处的重载无关 - 您根本不能指定三个这样的方法。如果调用者指定了三个参数,您希望调用哪个方法?

既然它们都做同样的事情,为什么还要三种方法呢?只需摆脱前两个。

于 2013-03-11T15:22:51.627 回答
1

您不能有两个或多个具有相同签名的方法。这意味着它们不能具有相同的名称和参数类型。这与将传递给方法的值无关。

正确的可能是:

public int Sum(int a, int b)
{
    return Sum(a, b, 0);
}

public int Sum(int a, int b, int c)
{
    return a + b + c;
}

编辑:

这是一篇有趣的 MSDN 文章,提供有关成员重载的指南。

于 2013-03-11T15:26:16.890 回答
0

您的方法签名(双,双,双)是相同的。在这种情况下,只需删除前两个实现。最后一个很可能已经按照您想要的方式运行。

于 2013-03-11T15:23:01.553 回答
0

你的最后两个 ComputePay (double, double, double) 是一样的。拥有默认变量不会使方法不同。只需使用第二个就可以了。

于 2013-03-11T15:24:04.993 回答