开发者

Convert IEnumerable to IEnumerable<T> when T isn't known until runtime

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.

Update

I can get a type object like this:

var first = results.Cast<object>().FirstOrDefault();
if (first != null)
{
    var type = first.GetType();

}

Update2

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(r开发者_StackOverflow中文版esults != 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.


Here's the code that worked for me:

    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("ToList").MakeGenericMethod(type);
            dynamic genericResults = castMethod.Invoke(null, new[] { results });
            Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
        }

    }        
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜