必须满足所有要求后才能显示可选参数

时间:2016-10-02 23:40:49

标签: c#

我正在尝试调试一些具有CalculateTuition方法的代码,其中一个参数名为credits。我在运行时获得的错误是"可选参数必须出现在所有必需参数之后"。  此应用程序的目的是演示可以使用一个,两个或三个参数调用方法。我无法弄清楚所需参数和可选参数之间的区别。谢谢你的时间!

public static void Main()
{
    Console.WriteLine("Tuition is {0}", Calculatetuition(15));
    Console.WriteLine("Tuition is {0}", CalculateTuition(15, 'O'));
    Console.WriteLine("Tuition is {0}", CalculateTuition(15, 'O', true));
}


public static double CalculateTuition(string code = "I", double credits,
         bool  scholarship = false)
{
    double tuition;
    const double RATE = 80.00;
    const double OUT_DISTRICT_FEE = 300.00;

    tuition = credits * RATE;
    if (code == 'I')
       tuition += OUT_DISTRICT_FEE;
    if (scholarship)
        tuition = 0;
    return tuition;
}

1 个答案:

答案 0 :(得分:2)

public static double CalculateTuition(string code = "I", double credits, bool  scholarship = false)

code是一个可选参数。如果调用者未提供code的值,则其默认值为"I"。但是,由于错误状态,可选参数必须不在必需参数之前。将您的方法签名(并相应地更新用法)更改为:

public static double CalculateTuition(double credits, string code = "I", bool scholarship = false)

或者使code成为必需参数

public static double CalculateTuition(string code, double credits, bool  scholarship = false)