Assembly.GetTypes () for nested classes

Assmbly.GetTpes () gets the types in the assembly, but if I also need a nested class (OrderLine), how can I do this? I know only the assembly name, not the class names, so GetType (Order + OrderLine) will not work.

public class Order { public class OrderLine { } } 
+6
reflection c #
source share
3 answers

I don't know if assembly.GetTypes() include nested classes. Assuming this is not the case, a method like the one below can iterate over all types of assemblies.

 IEnumerable<Type> AllTypes(Assembly assembly) { foreach (Type type in assembly.GetTypes()) { yield return type; foreach (Type nestedType in type.GetNestedTypes()) { yield return nestedType; } } } 

Edit:
MSDN has the following to say about Assembly.GetTypes

The returned array includes nested types.

So really my previous answer is not needed. You should find both Order and Order+OrderLine returned as types on Assembly.GetTypes .

+6
source share

Something like that:

 Assembly.GetTypes().SelectMany(t => new [] { t }.Concat(t.GetNestedTypes())); 
+4
source share

You can use the LINQ operator. I am not 100% sure what you are trying to do, but you can do something like this.

 Assembly.GetTypes().Where(type => type.IsSubclassOf(SomeType) && type.Whatever); 

Edit

If normal Assembly.GetTypes() does not return your nested class, you can CurrentType.GetNestedTypes() over the array and add everything you find in CurrentType.GetNestedTypes() to the array. as

  var allTypes = new List<Type>(); var types = Assembly.GetTypes(); allTypes.AddRange(types); foreach(var type in types) { allTypes.AddRange(type.GetNestedTypes()); } 
0
source share

All Articles