我刚刚做了一个快速测试,编译器优化了代码。这个基本示例 Main 方法。
public static void OptionalParamMethod(bool input, string input2 = null)
{
}
public static void Main(string[] args)
{
OptionalParamMethod(true);
OptionalParamMethod(false, "hello");
}
编译为此,以便编译器填充可选参数。
public static void Main(string[] args)
{
OptionalParamMethod(true, null);
OptionalParamMethod(false, "hello");
}
至于性能,您可能会认为可选参数有一点优势,因为只有一个方法调用,而不是像通常对重载方法那样的链式方法调用。下面的代码是编译输出以显示我正在谈论的内容。这不同之处 https://gist.github.com/iwantedue/7150746虽然这是相当学术性的,但我怀疑你在实践中是否会注意到。
public static void Main(string[] args)
{
OptionalParamMethod(true, null);
OptionalParamMethod(false, "hello");
OverloadParamMethod(true);
OverloadParamMethod(false, "hello");
}
public static void OptionalParamMethod(bool input, [Optional, DefaultParameterValue(null)] string input2)
{
Console.WriteLine("OptionalParamMethod");
}
public static void OverloadParamMethod(bool input)
{
OverloadParamMethod(input, null);
}
public static void OverloadParamMethod(bool input, string input2)
{
Console.WriteLine("OverloadParamMethod");
}