我有一个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
}
怎么做?
答案 0 :(得分:8)
您可以利用类型推断,但这需要您传递实例。这可以做到:
public static OrderMapper<T> ForFromEnumerable<T>(IEnumerable<T> dummy)
{
return new OrderMapper<T>();
}
用法:
var m = OrderMapper.ForFromEnumerable(listOfObjectsOfTypeY).Add("title", x => x.Title);
答案 1 :(得分:0)
使用具体类型会好得多 - 只需将匿名返回的linq查询投影到具体类型。
如果您必须支持它,您可能不得不诉诸dynamic
// no compile-time checking here.
OrderMapper<dynamic> m = OrderMapper.For<dynamic>().Add("title", x => x.Title);