使用可选参数

Nee*_*eta 4 c# optional-arguments

我有一个带有2个可选参数的方法.

public IList<Computer> GetComputers(Brand? brand = null, int? ramSizeInGB = null)
{
    return new IList<Computer>();
}
Run Code Online (Sandbox Code Playgroud)

我现在正尝试在其他地方使用此方法,我不想指定Brand参数,只是int但我使用此代码时遇到错误:

_order.GetComputers(ram);
Run Code Online (Sandbox Code Playgroud)

我收到的错误:

Error   1   The best overloaded method match for 'ComputerWarehouse.Order.GetComputers(ComputerWarehouse.Brand?, int?)' has some invalid arguments  C:\Users\avmin!\Documents\InnerWorkings Content\630dd6cf-c1a2-430a-ae2d-2bfd995881e7\content\T0062A2-CS\task\ComputerWarehouse\ComputerStore.cs 108 59  ComputerWarehouse
Error   2   Argument 1: cannot convert from 'int?' to 'ComputerWarehouse.Brand?'    C:\Users\avmin!\Documents\InnerWorkings Content\630dd6cf-c1a2-430a-ae2d-2bfd995881e7\content\T0062A2-CS\task\ComputerWarehouse\ComputerStore.cs 108 79  ComputerWarehouse
Run Code Online (Sandbox Code Playgroud)

Set*_*ers 9

如果要跳过其他可选参数,则必须指定可选参数的名称.

_order.GetComputers(ramSizeInGB: ram);
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 5

要允许编译器填充先前的参数,您需要指定后续参数的名称:

_order.GetComputers(ramSizeInGB: ram);
Run Code Online (Sandbox Code Playgroud)

基本上,C#编译器假定除非您指定任何参数名称,否则您提供的参数将按其他顺序排列.如果不为所有参数提供值,并且其余参数具有默认值,则将使用这些默认值.

因此所有这些都是有效的(假设适当的值为brandram):

_order.GetComputers(brand, ram);       // No defaulting
_order.GetComputers(brand);            // ramSizeInGB is defaulted
_order.GetComputers(brand: brand);     // ramSizeInGB is defaulted
_order.GetComputers(ramSizeInGB: ram); // brand is defaulted
_order.GetComputers();                 // Both arguments are defaulted
Run Code Online (Sandbox Code Playgroud)