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

问题描述 投票:1回答:1

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

我有一个FieldInfo对象,并在其上调用GetValue()

我得到了一个object回来。

在VisualStudio中检查这个对象,我发现它是一个“原型”,并且GetType()返回System.RuntimeType

在即时窗口中,我可以投射我的object as System.RuntimeType,然后我发现了一个AsType()方法,它返回我真实的打字对象。

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

如何从这个对象中获取一个打字对象?


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.

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


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

如果有一种不反思的方法,我会很想知道它吗?

c# reflection system.reflection
1个回答
2
投票

我倾向于认为,如果你在兔洞(或者,我想,通过镜子)这么远的地方,你应该放弃从静态类型系统中获益的任何借口,并且只是利用动态运行时间(假设您使用的是.NET 4或更高版本。

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

© www.soinside.com 2019 - 2024. All rights reserved.