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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/632570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:06:34  来源:igfitidea点击:

Cast received object to a List<object> or IEnumerable<object>

c#.net

提问by Sergio Romero

I'm trying to perform the following cast

我正在尝试执行以下演员

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

But I always end up with the following excepction:

但我总是以以下例外结束:

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

无法转换类型为“System.Collections.Generic.List 1[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.

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

Thank you.

谢谢你。

采纳答案by erikkallen

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

C# 4 将有协变和逆变模板参数,但在那之前你必须做一些非泛型的事情,比如

IList collection = (IList)myObject;

回答by Cameron MacFarland

How about

怎么样

List<object> collection = new List<object>((IEnumerable)myObject);

回答by andleer

You can't cast an IEnumerable<T> to a List<T>.

您不能将 IEnumerable<T> 转换为 List<T>。

But you can accomplish this using LINQ:

但是您可以使用 LINQ 完成此操作:

var result = ((IEnumerable)myObject).Cast<object>().ToList();

回答by Jon Skeet

Do you actually need more information than plain IEnumerablegives you? Just cast it to that and use foreachwith it. I face exactly the same situation in some bits of Protocol Buffers, and I've found that casting to IEnumerable(or IListto access it like a list) works very well.

你真的需要比普通IEnumerable给你更多的信息吗?只需将它投射到那个并使用foreach它。我在某些协议缓冲区中遇到了完全相同的情况,我发现强制转换IEnumerable(或IList像列表一样访问它)效果很好。

回答by Chris Holmes

Problem is, you're trying to upcast to a richer object. You simply need to add the items to a new list:

问题是,您正在尝试向上转换为更丰富的对象。您只需将项目添加到新列表中:

if (myObject is IEnumerable)
{
   List<object> list = new List<object>();
   var enumerator = ((IEnumerable) myObject).GetEnumerator();
   while (enumerator.MoveNext())
   {
      list.Add(enumerator.Current);
   }
}

回答by Manish Nayak

This Code worked for me

此代码对我有用

List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);

回答by IVSoftware

Have to join the fun...

必须加入乐趣...

    private void TestBench()
    {
        // An object to test
        string[] stringEnumerable = new string[] { "Easy", "as", "Pi" };

        ObjectListFromUnknown(stringEnumerable);
    }

    private void ObjectListFromUnknown(object o)
    {
        if (typeof(IEnumerable<object>).IsAssignableFrom(o.GetType()))
        {
            List<object> listO = ((IEnumerable<object>)o).ToList();
            // Test it
            foreach (var v in listO)
            {
                Console.WriteLine(v);
            }
        }
    }

回答by IVSoftware

You need to type cast using asoperator like this.

您需要像这样使用as运算符进行类型转换。

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