相关疑难解决方法(0)

将接收到的对象转换为List <object>或IEnumerable <object>

我正在尝试执行以下演员表

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

但我总是得到以下例外:

无法转换类型为'System.Collections.Generic.List 1[MySpecificType]' to type 'System.Collections.Generic.List1 [System.Object]'的对象

我真的需要这个工作,因为这个方法需要非常通用才能接收单个对象和两个未指定类型的集合.

这是可能的,还是有另一种方法来实现这一点.

谢谢.

.net c#

60
推荐指数
6
解决办法
17万
查看次数

为什么将List <double>显式转换为IEnumerable <object>会抛出异常?

根据这个MSDN引用 IEnumerable是协变的,这可以隐式地将对象列表转换为可枚举:

IEnumerable<String> strings = new List<String>();
IEnumerable<Object> objects = strings;
Run Code Online (Sandbox Code Playgroud)

在我自己的代码中,我编写了一行代码,当列表的项类型为class时,它是完美的Point(Point是一个简单的类,有三个属性double x,y,z):

var objects = (IEnumerable<object>)dataModel.Value;
// here property Value is a list that could be of any type. 
Run Code Online (Sandbox Code Playgroud)

但是当列表的项类型为double:时,上面的代码返回以下异常:

Unable to cast object of type System.Collections.Generic.List1[System.Double] 
to type System.Collections.Generic.IEnumerable1[System.Object].
Run Code Online (Sandbox Code Playgroud)

是什么区别stringdouble和是什么原因导致代码的工作string,但不是double

更新

根据这篇文章,我们可以简单地将一个列表转换为IEnumerable(没有类型参数),因为我只需要迭代项目并将新项目添加到列表中(实际上我根本不需要列出列表中的项目).我决定用这个:

var objects = (IEnumerable)dataModel.Value;
Run Code Online (Sandbox Code Playgroud)

但是如果您需要将列表中的项目投射到object并使用它们,Theodoros的答案就是您最常遵循的解决方案.

c# generics ienumerable casting

14
推荐指数
1
解决办法
1497
查看次数

标签 统计

c# ×2

.net ×1

casting ×1

generics ×1

ienumerable ×1