Search for IEnumerable Object Type

For most of the objects that I can do,

obj.getType().FullName 

But for the following code

 static void Main(string[] args) { IEnumerable<int> em = get_enumerable(); Console.WriteLine(em.GetType()); Console.Read(); } static IEnumerable<int> get_enumerable() { for (int i = 0; i < 10; i++) { yield return i; } } 

There is an exit,

ConsoleApplication1.Program + d__0

Where ConsoleApplication1 is an assembly and the program contains a class (not shown). Why doesn't it show IEnumerable and how can I make GetType more descriptive for this case?

+4
source share
2 answers

IEnumerable<T> is an open generic type. This is not a real type; it's just a function that builds specific (private) generic types of type IEnumerable<int> .

IEnumerable<int> is the interface; it is impossible to have an instance of the interface.

The iterator function actually returns an instance of a hidden compiler-generated class that implements IEnumerable<int> ; what you see from GetType() .

You want to find a generic type of an implementation type of type IEnumerable<T> :

 em.GetType().GetInterface("System.Collections.Generic.IEnumerable`1") .GetGenericArguments()[0] 
+7
source

IEnumerable is an interface, but GetType will return System.Type , which represents the class of the object, not the interface (s) that it implements.

When you use yield return , the C # compiler automatically generates a new class (called ConsoleApplication1.Program+d__0 in this case) that implements IEnumerable<int> (and IEnumerable ).

+2
source

Source: https://habr.com/ru/post/1489124/


All Articles