的方法使用匿名类型我有我使用如下的OrderMapper类:在接受通用
OrderMapper<Post> m = OrderMapper.For<Post>().Add("title", x => x.Title);
其中x是Post类型。问题是将其应用于匿名类型时。
var listOfAnonymousObjects = posts.SelectMany(x => x.PostsI18N, (Post, PostI18N) => new { Post, PostI18N });
OrderMapper<??> m = OrderMapper.For<??>().Add("title", x => x.Title);
其中x必须是listOfAnonymousObjects中的AnonymousObject类型。我的OrderMapper代码是:
public class OrderMapper {
public static OrderMapper<T> For<T>() {
return new OrderMapper<T>();
}
}
public class OrderMapper<T> {
private readonly Dictionary<String, LambdaExpression> _mappings = new Dictionary<String, LambdaExpression>();
public OrderMapper<T> Add<K>(String source, Expression<Func<T, K>> target) {
if (!_mappings.ContainsKey(source))
_mappings.Add(source, target);
return this;
}
public LambdaExpression this[String source] {
get {
LambdaExpression target;
return _mappings.TryGetValue(source, out target) ? target : null;
}
} // this
}
如何做到这一点?
为什么不能用一个具体的类,而不是匿名之一? – juharr
@亚历克斯:对不起?没有理解你的评论。 –
诀窍是使用类型推断,而不是手动指定泛型类型参数。看看LINQ是怎么做到的:) – Luaan