2012-11-09 30 views
4

我有一個有2個可選參數的方法。使用可選參數

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

現在我想在其他地方使用這種方法,我不想指定Brand參數,並使用此代碼只是int,但我得到的錯誤:

_order.GetComputers(ram); 

我的錯誤我正在接收:

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 

回答

9

如果您要跳過其他可選參數,則必須指定可選參數的名稱。

_order.GetComputers(ramSizeInGB: ram); 
+0

謝謝!這工作。 – Neeta

+0

你每天都會學到新的東西!謝謝! –

5

爲了讓更早參數由編譯器來填寫,你需要指定後來者的名​​字:

_order.GetComputers(ramSizeInGB: ram); 

基本上,C#編譯器假定,除非你指定的任何參數名稱,您提供的參數是按照附加順序。如果您沒有提供所有參數的值,並且其餘參數有默認值,那麼將使用這些默認值。

因此,所有的這些都有效(假設和brand適當的值ram):

_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 
2

正確的語法是結合使用命名參數與可選參數,就像這樣:

_order.GetComputers(ramSizeInGB: ram); 

只有當它們位於指定參數後面時,可選參數纔可以跳過(不使用命名參數),所以這可以:

_order.GetComputers(new Brand()); 

爲將這項

_order.GetComputers(); 

要看看爲什麼必須這樣做,可以考慮的方法具有這樣的特徵:

public void Method(double firstParam = 0, long secondParam = 1) 

Method(3); 

這裏編譯器不能推斷如果開發人員打算使用第一個參數或第二個參數調用該方法,則唯一的區別方法是明確指出哪些參數映射到哪些參數。