lundi 28 septembre 2015

Get ctor argument used in field's initializer using reflection

My assembly has multiple classes which have fields like this:

private static Foo MyFoo = new Foo(typeof(Bar));

The argument typeof(Bar) differs for each class.

In my unit tests, I need to extract that argument dynamically.

I can find all classes, and filter for those with a static Foo field. I then have a FieldInfo.

But then I don't know how to get that argument?

What I'm doing so far:

var argument =
  Assembly.GetExecutingAssembly().Select(name => Assembly.Load(name.FullName))
  .SelectMany(assembly => assembly.GetTypes()).Where(type => type.IsClass)
  .Where(type => type.GetFields(BindingFlags.Static).Any(fieldinfo => fieldinfo.FieldType == typeof(Foo)))
  .Select(fieldinfo => fieldinfo.FieldType == typeof(Foo));





Aucun commentaire:

Enregistrer un commentaire