![](/img/trans.png)
[英]Casting generic to interface type - Unable to cast object of type 'System.RuntimeType' to type
[英]Given an object that I happen to know is a System.RuntimeType how do I get a typed object out?
我做了一些可怕的DI反射:(
我已經得到一個FieldInfo
對象,並在其上調用了GetValue()
。
我拿回了一個object
。
在Visual Studio中檢查此對象,我發現它是一個“原型”,並且GetType()
返回System.RuntimeType
。
在立即窗口中,我可以將object as System.RuntimeType
AsType()
object as System.RuntimeType
,然后發現一個AsType()
方法,該方法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”擴展方法可以使此操作更容易)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.