2011-12-05 27 views
1

目前我正在學習LINQ,執行此查詢時:LINQ,類型不能被推斷

public static class Linq 
     { 
      // Returns the given anonymous method as a lambda expression 
      public static Expression<Func<Int32, Int32>> 
       Expr<T, R>(Expression<Func<Int32, Int32>> f) 
      { 
       return f; 
      } 
      // Returns the given anonymous function as a Func delegate 
      public static Func<T, R> 
       Func<T, R>(Func<T, R> f) 
      { 
       return f; 
      } 

    } 

//main Fun 

var expr = Linq.Expr((Int32 a, Int32 b) => a + b); 
var fun = Linq.Func((int a, int b) => a + b); 

我收到以下錯誤Linq.Expr<T,R>(System.Linq.Expressions.Expression<System.Func<int,int>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.錯誤。我究竟做錯了什麼?

+1

你是什麼'靜態類Linq'這裏的成員呢?他們只是完全回報傳遞給他們的東西。 –

+0

@AndrewBarber:不完全正確。嘗試使用這些方法編寫最後兩行。您需要執行強制轉換或顯式指定變量的類型。這些方法是一個捷徑。快捷鍵在「short to type」中:-) –

+0

@DanielHilgarth嗯,我說的是真的,但我明白你的意思 - 他們爲編譯器提供了一個具體的類型來知道如何處理'var'關鍵字。現在有意義。 :-)編輯:我發佈的內容不完整,從這個意義上講,並不完全正確。是:) –

回答

2

如果你想有兩個輸入參數和一個返回值,你需要使用一個Func<T1, T2, TRet>,即一個有三個參數。

0

我想你想要這樣的:

public static class Linq { 
// Returns the given anonymous method as a lambda expression 
public static Expression<Func<T1, T2, R>> 
        Expr<T1, T2, R>(Expression<Func<T1, T2, R>> f) 
     { 
    return f; 
} 
// Returns the given anonymous function as a Func delegate 
public static Func<T1, T2, R> Func<T1, T2, R>(Func<T1, T2, R> f) 
{ 
    return f; 
}} 

用法:

var expr = Linq.Expr<int, int, int>((a, b) => a + b); 
var fun = Linq.Func<int, int, int>((a, b) => a + b);