给定一个我碰巧知道的对象是 System.RuntimeType 我如何得到一个类型化的对象?

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

我做了一些可怕的 DI 反射:(

我得到了一个 FieldInfo 对象并在其上调用了 GetValue()

我得到了 object 回报。

在 VisualStudio 中检查这个对象,我发现它是一个 "prototype",GetType() returns System.RuntimeType.

在直接 window 中,我可以转换我的 object as System.RuntimeType,然后我发现一个 AsType() 方法,它 returns 我是我真正的类型化对象。

不幸的是,当我尝试在我的代码中编写它时,我被告知 System.RuntimeType 是一个内部类型,因此我不能使用它:(.

我怎样才能从这个对象中得到类型对象?


完整代码:

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


请注意,我真的不知道对象的类型是什么——我正在反思的东西本身就是一个反思……我正在尝试从我的 DI 框架中提取绑定信息。

根本问题的解决方案很有用,但我确实想知道如何与这个 System.RuntimeType 对象交互。


更新: Evk 提出了一个 "moah reflection!" 解决方案,它确实有效。 (查看评论)

如果有非反射方法,我很想知道吗?

我倾向于认为,如果你已经陷入困境(或者,我想,通过窥镜),你应该放弃任何从静态类型系统中受益的假装,而只是利用动态运行时(假设您使用的是 .NET 4 或更高版本)。

查看 https://blogs.msdn.microsoft.com/davidebb/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code/ 示例,了解代码可以更加整洁(以及方便的 'AsDynamic' 扩展方法,使这更容易)。