vendredi 8 septembre 2017

How to dynamically access static fields of unknown closed generic types?

Let's assume I have a generic class defined as follows:

public class MyThing<T> {
     private static int NumberOfCallsToFoo;
     public void Foo(T item) {
          NumberOfCallsToFoo++;
          ...
     }
}

Later I want to collect all the number of calls to any closed type of MyThing without knowing all possible type parameters so I can print a list such as:

  • Number of calls to MyThing<int>.Foo(): 142
  • Number of calls to MyThing<Bar>.Foo(): 39
  • etc.

So what I need is a way to dynamically get all created closed types from the run-time. Something like:

public IEnumerable<Type> GetClosedMyThingTypes() {
    // what to put here?
}

Then I could use reflection to get the NumberOfCallsToFoo field. The purpose of this is to trace a huge system with many types and assemblies involved.





Aucun commentaire:

Enregistrer un commentaire