我有以下类型推断“失败”的情况(至少失败了我希望它做了什么)。基本上,我有一个方法接受泛型类型的数组。我需要将该数组类型化为匿名对象,但类型推断无法执行此操作。
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"
});
}
我认为原因是因为数组类型是从其内容而不是其上下文推断出来的。这似乎使得在这种情况下无法使用匿名类型。
有什么想法绕过这个?
答案 0 :(得分:-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));
}