Question

I am working on a solution that extracts all the class associations between each other. If we click a class in the object browser we can see the option Find All References. I want something similar that finds the associations a class has to other classes. How can we find them using Reflection?

I am interested in Extracting

  1. Composition Relationship:
  2. Aggregation Relationship
  3. Association Relationship
  4. Inheritance
Was it helpful?

Solution

You can use Reflection in order to list all properties, fields and methods (and more) of a class. You would have to inspect these and determine their types and parameter lists. Probably it would be a good idea to discard types from the System namespace.

Type t = typeof(MyClass);

// Determine from which type a class inherits
Type baseType = t.BaseType;

// Determine which interfaces a class implements
Type[] interfaces = t.GetInterfaces();

// Get fields, properties and methods
const BindingFlags bindingFlags =
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
FieldInfo[] fields = t.GetFields(bindingFlags);
PropertyInfo[] properties = t.GetProperties(bindingFlags);
MethodInfo[] methods = t.GetMethods(bindingFlags);

foreach (var method in methods) {
    // Get method parameters
    ParameterInfo[] parameters = method.GetParameters();
}

Intellisense will tell you (almost) all the secrets of FieldInfo, PropertyInfo, MethodInfo and ParameterInfo. You might also consider examining the generic parameters of the class, events and more.

OTHER TIPS

You would need to parse the generated IL code, preferable with an understanding how they work. You can retrieve the IL code by calling MethodBase.GetMethodBody followed by MethodBody.GetILAsByteArray.

You need to parse every byte according to the OpCodes enum. You'll also need to handle all opcode data, like offsets and tokens, since you shouldn't parse them as actual opcodes. Take the OpCodes.Ldstr opcode for example; it consists of 0x72 followed by a token. This token is four bytes that should be parsed as an Int32, and can be resolved using Module.ResolveString (since you know that ldstr has a string token). You can get a Module instance from Assembly.AssemblyManifestModule.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top