更新时间:2023-02-14 10:56:13
var elementType = ...
var results = ...
var castMethod = typeof(Enumerable).GetMethod(Cast)。MakeGenericMethod(elementType );
var genericResults = castMethod.Invoke(null,new [] {results});
IEnumerable< T>
(其中 T
是由 elementType
变量)。但请记住,静态地, genericResults
仍然是类型 object
;没有办法告诉编译器它是 IEnumerable< T>
,因为 T
不是静态的。 How can I convert IEnumerable
to IEnumerable<T>
when T isn't known until runtime?
I have a method that absolutely needs an IEnumerable<T>
where T isn't known until runtime and T
must be the actual type and not an ancestor type like object.
I'm betting the reflection API allows for something like this but I don't know exactly how.
I can get a type object like this:
var first = results.Cast<object>().FirstOrDefault();
if (first != null)
{
var type = first.GetType();
}
The "method" I was referring to was actually the Setter of the WPF DataGrid's ItemSource property.
The problem I'm having is that if I don't pass it an IEnumerable<T>
the rows generated in the Datagrid are all blank, as if it's method of reflecting over the properties of T
is not working and it can't generate columns.
Even using this code has this unwanted effect:
public CollectionResultWindow(IEnumerable results)
{
Contract.Requires(results != null, "results is null.");
InitializeComponent();
DataContext = this;
var first = results.Cast<object>().FirstOrDefault();
if (first != null)
{
Type type = first.GetType();
var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(type);
dynamic genericResults = castMethod.Invoke(null, new[] { results });
Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
}
}
var elementType = ...
var results = ...
var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType);
var genericResults = castMethod.Invoke(null, new[] { results });
The genericResults
variable refers to an object of type IEnumerable<T>
(where T
is the type represented by the elementType
variable). But keep in mind that statically, genericResults
is still of type object
; there is no way to tell the compiler that it is an IEnumerable<T>
, since T
isn't known statically.