Casting an object to IEnumerable where T is not known

后端 未结 2 602
生来不讨喜
生来不讨喜 2021-02-13 11:50

I am trying to play with Reflection and ran into the following situation.

In the following code, let\'s assume that the \'obj\' can be of types IEnumerable<>

2条回答
  •  囚心锁ツ
    2021-02-13 12:30

    Well, since you don't know the actual type of the items until runtime, you don't need to use the generic IEnumerable interface; just use the non-generic one, IEnumerable (the generic one inherits from it):

    private void WriteGenericCollection(object obj)
    {
        IEnumerable enumerable = (IEnumerable)obj;
        foreach(object item in enumerable)
        {
            ...
        }
    }
    

提交回复
热议问题