输入'支付'已经定义了一个名为'ComputePay'使用相同的参数类型

本文关键字:ComputePay 类型 参数 定义 支付 输入 一个 | 更新日期: 2023-09-27 18:03:25

我似乎不明白这里有什么问题。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;
    }
}

输入'支付'已经定义了一个名为'ComputePay'使用相同的参数类型

我不确定我做错了什么。

你有三个方法,它们都有三个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)

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

既然它们都做同样的事情,为什么你想要三个方法呢?去掉前两个

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

正确的可能是:

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文章,给出了关于成员重载的指导方针。

你的方法签名(double, double, double)是一样的。在本例中,只需删除前两个实现。最后一个人很可能已经按照你想要的方式行事了。

您的最后两个ComputePay (double, double, double)是相同的。拥有默认变量并不会使方法有所不同。只要使用第二个,就可以了。