通用 List的数据类型可以吗?被暗示?
是否有隐式方法告诉通用集合使用传入 IEnumerable
数据的 Type
?
假设任何类型都可以传入,因为它可能已被隐藏(例如通过 IQueryable)并且可能包含匿名类型。
var enumerableThings = //... enumerable<T> obtained from somewhere.
关键是T是未知的。
我想创建可枚举事物的主要类型的 List
:
var listOfThoseThings = new List<???>(enumerableThings);
C#/.NET 中有许多有趣的机制。如果我发现有能力执行这项任务,我不会感到惊讶;然而目前我无法找到一种简洁的方式。
Is there an implicit way to tell a generic collection to use the Type
of the incoming IEnumerable<T>
data?
Assume any Type can be incoming because it might have been obscured, for example, through IQueryable and might contain an anonymous Type.
var enumerableThings = //... enumerable<T> obtained from somewhere.
The point is T is unknown.
I want to create a List<T>
of the primary Type of the enumerable thing:
var listOfThoseThings = new List<???>(enumerableThings);
There are many interesting mechanisms in C#/.NET. I wouldn't be surprised to find the ability to carry out this task; however at the moment a concise way evades me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是为什么
ToList()
扩展方法 存在。与
List
构造函数不同,它可以使用类型推断来隐式指定泛型参数。This is why the
ToList()
extension method exists.Unlike the
List<T>
constructor, it can use type inference to implcitly specify the generic parameter.只是为了扩展 SLAks 的(正确)答案。
当您调用
ToList
时,即调用泛型方法Enumerable.ToList(IEnumerablesource)
。然后,编译器以正常方式使用泛型类型推断来计算T
。请注意,目前虽然有对
ToList
、ToDictionary
和ToArray
的调用,但没有HashSet
的等效项。不过写起来很容易:做这种事情是使用类型参数构造泛型类型实例的唯一方法,该类型参数是匿名类型,缺乏泛型。这是一份好工作,很简单:)
Just to expand on SLaks' (correct) answer.
When you call
ToList
, that's calling the generic methodEnumerable.ToList<T>(IEnumerable<T> source)
. The compiler then uses generic type inference in the normal way to work outT
.Note that at the moment although there are calls for
ToList
,ToDictionary
andToArray
, there's no equivalent forHashSet
. It's very easy to write though:Doing this sort of thing is the only way of constructing an instance of a generic type with a type argument which is an anonymous type, short of generics. It's a good job it's easy :)
无法直接执行此操作,但可以通过方法类型推断间接完成
There is no way to directly do this however it can be indirectly done via method type inference