[英]Use an Anonymous type on a method that accepts generic
I have an OrderMapper class which I use as follows: 我有一个OrderMapper类,我使用如下:
OrderMapper<Post> m = OrderMapper.For<Post>().Add("title", x => x.Title);
Where x is of type Post. 其中x是Post类型。 The problem is when applying it to anonymous types.
问题是将其应用于匿名类型时。
var listOfAnonymousObjects = posts.SelectMany(x => x.PostsI18N, (Post, PostI18N) => new { Post, PostI18N });
OrderMapper<??> m = OrderMapper.For<??>().Add("title", x => x.Title);
Where x must be of type AnonymousObject in listOfAnonymousObjects. 其中x必须是listOfAnonymousObjects中的AnonymousObject类型。 My OrderMapper code is:
我的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
}
How to do this? 这该怎么做?
You can take advantage of type inference, but that requires you to pass along an instance. 您可以利用类型推断,但这需要您传递实例。 This could do:
这可以做到:
public static OrderMapper<T> ForFromEnumerable<T>(IEnumerable<T> dummy)
{
return new OrderMapper<T>();
}
Usage: 用法:
var m = OrderMapper.ForFromEnumerable(listOfObjectsOfTypeY).Add("title", x => x.Title);
You're much better off using concrete types - just project your anonymous-returning linq queries to a concrete type. 使用具体类型要好得多 - 只需将匿名返回的linq查询投影到具体类型即可。
If you must support it, you're probably going to have to resort to dynamic
如果你必须支持它,你可能不得不求助于
dynamic
// no compile-time checking here.
OrderMapper<dynamic> m = OrderMapper.For<dynamic>().Add("title", x => x.Title);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.