2014-02-24 67 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