我做了一些可怕的DI反射:(
我有一个FieldInfo
对象,并在其上调用GetValue()
。
我得到了一个object
回来。
在VisualStudio中检查这个对象,我发现它是一个“原型”,并且GetType()
返回System.RuntimeType
。
在即时窗口中,我可以投射我的object as System.RuntimeType
,然后我发现了一个AsType()
方法,它返回我真实的打字对象。
不幸的是,当我尝试在我的代码中写这个时,我被告知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
根问题的解决方案很有用,但我确实想知道如何与这个System.RuntimeType
对象进行交互。
如果有一种不反思的方法,我会很想知道它吗?
我倾向于认为,如果你在兔洞(或者,我想,通过镜子)这么远的地方,你应该放弃从静态类型系统中获益的任何借口,并且只是利用动态运行时间(假设您使用的是.NET 4或更高版本。
请参阅https://blogs.msdn.microsoft.com/davidebb/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code/以获取代码可以更整洁的示例(以及一个方便的'AsDynamic'扩展方法,以使这更容易)。