Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

c# - How to get all types in a referenced assembly?

For whatever reason, I can't seem to get the list of types in a referenced assembly. Not only that, I can't even seem to be able to get to this referenced assembly.

I tried AppDomain.CurrentDomain.GetAssemblies(), but it only returns assemblies that have already been loaded into memory.

I tried Assembly.GetExecutingAssembly().GetReferencedAssemblies(), but this just returns mscorlib.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note that Assembly.GetReferencedAssemblies only includes a particular assembly if you actually use a type in that assembly in your assembly (or a type that you use depends on a type in that assembly). It is not enough to merely include an assembly in the list of references in Visual Studio. Maybe this explains the difference in output from what you expect? I note that if you're expecting to be able to get all the assemblies that are in the list of references in Visual Studio using reflection that is impossible; the metadata for the assembly does not include any information about assemblies on which the given assembly is not dependent on.

That said, once you've retrieved a list of all the referenced assemblies something like the following should let you enumerate over all the types in those assemblies:

foreach (var assemblyName in Assembly.GetExecutingAssembly().GetReferencedAssemblies()) {
    Assembly assembly = Assembly.Load(assemblyName);
    foreach (var type in assembly.GetTypes()) {
        Console.WriteLine(type.Name);
    }
}

If you need the assemblies that are referenced in Visual Studio then you will have to parse the csproj file. For that, check out the ItemGroup element containing Reference elements.

Finally, if you know where an assembly lives, you can load it using Assembly.LoadFile and then essentially proceed as above to enumerate over the types that live in that loaded assembly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...