2010-07-22 18 views
2

我無法理解在C#3.0中傳遞委託的規則是什麼。最後的.Max()給出瞭如下所示的編譯錯誤,但我無法理解該情況與其他任何情況之間的顯着差異。爲什麼這個命名函數不允許在C#中作爲Func <>參數傳遞?

int NamedIdentity(int val) { return val; } 
Func<int, int> Identity = x => x; 

void Main() { 
    var range = Enumerable.Range(1, 10); 

    range.Max(); 
    range.Max(x => x); 
    range.Max(Identity); 
    range.Max((Func<int, int>) NamedIdentity); 
    range.Max(new Func<int, int>(NamedIdentity)); 

    // this line gives compile error 
    range.Max(NamedIdentity); 
    /* The call is ambiguous between the following methods or properties: 
    * 'System.Linq.Enumerable.Max<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int,decimal>)' and 
    * 'System.Linq.Enumerable.Max<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int,decimal?>)' 
    */ 
} 

爲什麼不能編譯?我的理解是NamedIdentity被宣佈爲Func<int, int>,所以它不需要被鑄造,雖然顯然我錯了。一個線索是編譯錯誤正在談論Decimal s,即使沒有在代碼中的任何地方被引用。那個是從哪裏來的?函數引用是否可以隱式轉換爲相同簽名的委託?

回答

相關問題