Search code examples
c#reflectionsystem.reflection

Given an object that I happen to know is a System.RuntimeType how do I get a typed object out?


I've done some hideous DI reflection :(

I've gotten a FieldInfo object and called GetValue() on it.

I get an object back.

Examining this object in VisualStudio, I discover that it is a "prototype", and that GetType() returns System.RuntimeType.

In the immediate window, I can cast my object as System.RuntimeType, and then I discover an AsType() method, which returns me my real, typed object.

Unfortunately, when try to write this in my code, I'm told that System.RuntimeType is an internal type, and thus I can't use it :(.

How can I get a typed object out of this object?


Full code:

KernelBase baseKernel = (KernelBase)ninjectKernel;
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
FieldInfo field = typeof(KernelBase).GetField("bindings", flags);

Multimap<Type, IBinding> allBindingsPerTypeMap = (Multimap<Type, IBinding>)field.GetValue(baseKernel);

var aBinding = allInterfaceTypesWithAllBindings.First(pair => pair.InterfaceType.Name.Contains("FilePath")).Binding;
var aBindingTarget = aBinding .BindingConfiguration.ProviderCallback.Target;

var prototype = aBindingTarget.GetType().GetField("prototype").GetValue(aBindingTarget);

// prototype is an object, which I'd like to turn into a real type.
var runtimeType = prototype.GetType(); // this returns System.RuntimeType


Note that I genuinely don't actually know what the type of the object is - the thing I'm reflecting on, is itself a piece of reflection ... I'm trying to extract binding info from my DI framework.

Solutions to the root problem are useful, but I do actually want to know how to interact with this System.RuntimeType object.


UPDATE: Evk suggested a "moah reflection!" solution, which does indeed work. (See comments)

If there's a non-reflection approach, I'd be keen to know it though?


Solution

  • I tend to think that if you're this far down the rabbit hole (or, I suppose, through the looking glass), you should give up any pretence of benefitting from a static type system, and just take advantage of the dynamic runtime (assuming you're on .NET 4 or greater).

    See https://blogs.msdn.microsoft.com/davidebb/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code/ for an example of how much tidier the code can be (and a handy 'AsDynamic' extension method to make this easier).