2014-02-24 95 views
-1

我有下列類型推理「失敗」的情況下(至少對我所希望的失敗)。基本上,我有一個方法接受一個泛型類型的數組。我需要該數組來鍵入匿名對象,但類型推斷無法做到這一點。類型推斷失敗

private void foo<T>(IEnumerable<T> items, Func<T, Object>[] propertySelector) { } 

    public void Main() 
    { 
     var peeps = new[] 
     { 
      new {FirstName = "Taco", LastName = "King"}, 
      new {FirstName = "Papa", LastName = "Georgio"} 
     }; 

     foo(peeps, new[] 
     { 
      an => an.FirstName, //Error cannot infer type of "an" 
      an => an.LastName //Error cannot infer type of "an" 
     }); 
    } 

我相信原因是因爲數組類型從它的內容推斷,而不是它的上下文。這似乎使得在這種情況下不可能使用匿名類型。

任何想法在此方式?

回答

-1

在給出的示例中,可以將propertySelector更改爲params參數,然後單獨傳遞每個函數而不是數組。如果你不能因爲某些原因使用params,那麼像這樣的輔助函數將工作:

/// <summary> 
    /// Allows the use of type inference to get selector functions for the type of an enumerable. 
    /// </summary> 
    /// <typeparam name="T">The type of the enumerable.</typeparam> 
    /// <param name="enumerable">The enumerable.</param> 
    /// <param name="selectors">A set of selectors to return.</param> 
    /// <returns>The selectors passed in.</returns> 
    public static Func<T, Object>[] GetSelectors<T>(
     IEnumerable<T> enumerable, 
     params Func<T, Object>[] selectors) 
    { 
     return selectors; 
    } 

所以,你的例子將成爲:

private void foo<T>(IEnumerable<T> items, Func<T, Object>[] propertySelector) { } 

public void Main() 
{ 
    var peeps = new[] 
    { 
     new {FirstName = "Taco", LastName = "King"}, 
     new {FirstName = "Papa", LastName = "Georgio"} 
    }; 

    foo(peeps, GetSelectors(peeps, an => an.FirstName, an => an.LastName)); 
} 
+0

你剛纔問一個問題,所以你能回答自己呢? – 48klocs

+0

是wt *,只是立即回答。我認爲那傢伙有兩個賬戶,只是用另一個回答自己,以得到點...跛腳 – AAlferez

+0

這是鼓勵的SO - 請參閱:http://stackoverflow.com/help/self-answer – McAden