开发者

Problem with IEnumerable in Reflection [duplicate]

开发者 https://www.devze.com 2023-03-05 07:14 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: How to iterate the List in Reflection
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How to iterate the List in Reflection

Problem with IEnumerable in Reflection

Hi,

I am facing a problem while Iter开发者_JAVA技巧ating the List in reflection.

var item = property.GetValue(obj,null); // We dont know the type of obj as it is in Reflection.

foreach(var value in (item as IEnumerable))
 {
   //Do stuff
  }

If i do this i will get the error like

Using the generic type 'System.Collections.Generic.IEnumerable' requires 1 type arguments

Please help me.


There's a difference between the type IEnumerable and the generic type IEnumerable<T>. Currently it thinks you mean the generic one as you've included the namespace System.Collections.Generic; The error message is complaining because you've not written the IEnumerable<T> generic type correctly.

The non-generic IEnumerable type is declared in the System.Collections namespace, so add a reference to it. (using System.Collections;).

If you did mean to use the generic type then you should have something like this: foreach(var value in (item as IEnumerable<string>)) where string is the type of object item enumerates over.

See IEnumerable and IEnumerable<T> as well as this information about generic types.


As stated in the comments you already asked this question. This instance though is having a slightly different issue. You are getting a compiler error because you are including System.Collections.Generic namespace in your source file (top using clauses). That namespace contains the generic version of IEnumerable -> IEnumerable<T>. Your cast fails because of that. If you want to use IEnumerable add "using System.Collections".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号