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

后端 未结 8 1565
佛祖请我去吃肉
佛祖请我去吃肉 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<object> list = new List<object>();
       var enumerator = ((IEnumerable) myObject).GetEnumerator();
       while (enumerator.MoveNext())
       {
          list.Add(enumerator.Current);
       }
    }
    
    0 讨论(0)
  • 2020-12-08 00:21

    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);
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-08 00:23

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

    But you can accomplish this using LINQ:

    var result = ((IEnumerable)myObject).Cast<object>().ToList();
    
    0 讨论(0)
  • 2020-12-08 00:24

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

    0 讨论(0)
  • 2020-12-08 00:26

    This Code worked for me

    List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);
    
    0 讨论(0)
  • 2020-12-08 00:33

    How about

    List<object> collection = new List<object>((IEnumerable)myObject);
    
    0 讨论(0)
提交回复
热议问题