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

后端 未结 8 1602
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 23:52

I\'m trying to perform the following cast

private void MyMethod(object myObject)  
{  
    if(myObject is IEnumerable)  
    {
        List c         


        
      
      
      
8条回答
  •  心在旅途
    2020-12-08 00:20

    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 list = new List();
       var enumerator = ((IEnumerable) myObject).GetEnumerator();
       while (enumerator.MoveNext())
       {
          list.Add(enumerator.Current);
       }
    }
    
        

    提交回复
    热议问题