转换/施放了IEnumerable IEnumerable的到LT&; T> [英] Convert / Cast IEnumerable to IEnumerable<T>

查看:101
本文介绍了转换/施放了IEnumerable IEnumerable的到LT&; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类(Web控件),有IEnumerable类型的属性,愿与使用LINQ的参数来工作。

有什么办法投/转换/通过反射的IEnumerable&LT调用; T>在编译时不知道类型?

 方法无效(IEnumerable的源)
{
    VAR枚举= source.GetEnumerator();    如果(enumerator.MoveNext())
    {
        VAR类型= enumerator.Current.GetType();
        方法2<&型GT;(源); //这个不行!我知道!
    }
}方法二无效LT&; T>(IEnumerable的< T>源){}


解决方案

方法2 真正关心它得到什么类型?如果没有,你可能只需要调用演员LT;对象>()

  void方法(IEnumerable的源)
{
    方法2(source.Cast&所述;对象>());
}

如果你一定要得到正确的类型,你需要使用反射。

是这样的:

  MethodInfo的方法= typeof运算(的MyType).GetMethod(方法2);
MethodInfo的通用= method.MakeGenericMethod(类型);
generic.Invoke(这一点,新的对象[] {源});

这不是理想的,虽然...特别是,如果源不是的究竟的一个的IEnumerable<类型> 则调用将失败。例如,如果第一个元素恰好是一个字符串,但来源是列表与LT;对象> ,你就会有问题。

I have a class (A web control) that has a property of type IEnumerable and would like to work with the parameter using LINQ.

Is there any way to cast / convert / invoke via reflection to IEnumerable<T> not knowing the type at compile time?

Method void (IEnumerable source)
{
    var enumerator = source.GetEnumerator();

    if (enumerator.MoveNext())
    {
        var type = enumerator.Current.GetType();
        Method2<type>(source); // this doesn't work! I know!
    }
}

void Method2<T>(IEnumerable<T> source) {}

解决方案

Does your Method2 really care what type it gets? If not, you could just call Cast<object>():

void Method (IEnumerable source)
{
    Method2(source.Cast<object>());
}

If you definitely need to get the right type, you'll need to use reflection.

Something like:

MethodInfo method = typeof(MyType).GetMethod("Method2");
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(this, new object[] {source});

It's not ideal though... in particular, if source isn't exactly an IEnumerable<type> then the invocation will fail. For instance, if the first element happens to be a string, but source is a List<object>, you'll have problems.

这篇关于转换/施放了IEnumerable IEnumerable的到LT&; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆