开发者

Assembly.GetTypes() for nested classes

Assmbly.GetTpes() gets the types in the assembly but if I also wants nested class (OrderLine) how do I do that开发者_StackOverflow中文版? I only know the name of the assembly, not the class names so GetType(Order+OrderLine) will not work.

public class Order
{
  public class OrderLine
  {
  }
}


I don't know if assembly.GetTypes() is supposed to include nested classes. Assuming it doesn't, a method like the following could iterate over all the assembly's types.

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 above answer shouldn't be necessary. You should find both Order and Order+OrderLine returned as types by Assembly.GetTypes.


Something like this:


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


You can use a LINQ statement. I'm not 100% sure what you're trying to do, but you can do something like this.

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

Edit

If the normal Assembly.GetTypes() isn't returning your nested class, you could iterate over the array and add everything you find in CurrentType.GetNestedTypes() to the array. like

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜