You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mchsamples-.net-core/ex_036_001_Reflection
Marc CHEVALDONNE 88ac908fc7
end of .NET5.0 update
2 years ago
..
Solution end of .NET5.0 update 2 years ago
README.md Added a sample about Reflection 5 years ago

README.md

How to use reflection to explore an assembly?

or

How to use reflection to dynamically add a plugin to an application?

This sample is made of three projects. Be careful with the role and moreover, the links between each other.

1) ex_036_001_Mammifère.csproj

This assembly contains a Mammifère class with a simple Name property and compiles to a dll in the ex_036_001_Reflection\bin directory.

2) ex_036_001_ChatChienOiseau.csproj

This assembly contains three classes:

  • 2 of them are inheriting from Mammifère (Chat and Chien),
  • the other one is not inheriting from Mammifère (Oiseau).

Important: this assembly references the first one, and compiles to a dll into the ex_036_001_Reflection\plugin directory.

3) Applications\ex_036_001_Reflection.csproj

This assembly compiles to an exe in the ex_036_001_Reflection\bin directory. It references the first assembly, but does not reference the second assembly.

  • First, it parses the plugin folder and gets all files :
DirectoryInfo folder = new DirectoryInfo(Directory.GetCurrentDirectory().ToString()+"..\\..\\..\\plugin\\");F
ileInfo[] files = folder.GetFiles();
  • Next, it filters these files and launches an assembly analysis on .dll files only
foreach (FileInfo file in files.Where(f => f.Extension.Equals(".dll")))
{
    AnalyseDLL(file.FullName);
}
  • In this AnalyseDLL(string filePath) method, first, it loads the assembly:
Assembly a = Assembly.LoadFile(filePath);
  • then, it gets all the exported types of this assembly (all public types):
Type[] types = a.GetExportedTypes();
  • for each type t in types, it then writes its name in the Console, and tests if it's a subclass of Animal.Mammifère
Write(t.Name);

if(t.GetTypeInfo().IsSubclassOf(typeof(Animal.Mammifère)))
{
    //
}

Remember that this Console App does not reference the assembly where the classes Chat, Chien and Oiseau are defined. It only references the first assembly with the Animal.Mammifère class, so this is the only class it knows at compile-time. It discovers the others by reflection.

Now you can explore the types (if they are primitive, interfaces, abstract, delegate, generics ...) and their members (methods, properties...). Have fun!

Marc Chevaldonné, 27th of may 2019