铸造接收到的对象到List<对象>或IEnumerable的<对象> [英] Cast received object to a List<object> or IEnumerable<object>

查看:126
本文介绍了铸造接收到的对象到List<对象>或IEnumerable的<对象>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行以下投

private void MyMethod(object myObject)  
{  
    if(myObject is IEnumerable)  
    {
        List<object> collection = (List<object>)myObject;  
        ... do something   
    }  
    else  
    {  
        ... do something  
    }  
}

但我总是落得以下excepction:

But I always end up with the following excepction:

无法转换类型的对象System.Collections.Generic.List 1 [MySpecificType]'输入'System.Collections.Generic.List 1 [System.Object的]

Unable to cast object of type 'System.Collections.Generic.List1[MySpecificType]' to type 'System.Collections.Generic.List1[System.Object]'

我真的需要这个工作,因为这种方法需要非常通用的接受单个对象和集合两种不明类型。

I really need this to work because this method needs to be very generic to receive single objects and collections both of unspecified types.

这是可能的,或者是有完成此的另一种方式。

Is this possible, or is there another way of accomplishing this.

感谢你。

推荐答案

C#4将有协变和逆变模板参数,但在那之前,你必须做一些非通用像

C# 4 will have covariant and contravariant template parameters, but until then you have to do something nongeneric like

IList collection = (IList)myObject;

这篇关于铸造接收到的对象到List&LT;对象&gt;或IEnumerable的&LT;对象&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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