// Assuming this object is allocated somewhere else
var dict = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"}
};
// allocate a handle for it so it won't get destroyed by GC
var handle1 = GCHandle.Alloc(dict);
// Get internal representation of this object
IntPtr ptrObj = GCHandle.ToIntPtr(handle1);
// Assuming now we are in another module
var handle2 = GCHandle.FromIntPtr(ptrObj); // Get handle from IntPtr of this object
var objDict = handle2.Target; // Get object
// How to convert it back to Dictionary?
// When debug, I know its type is Dictionary<int, string>,
// but how I can know here?
// This conversion is not working
var myDict = (Dictionary<object, object>)objDict;
// Anyway to cast it from GetType()?
var myDict = (objDict.GetType())objDict;
在一個模塊中,我創建了一個字典并轉換為IntPtr(用于 PInvoke 呼叫)。在另一個模塊中,我從IntPtr獲取字典物件,這是一個通用物件。如何將其轉換回原始型別,以便可以像這樣使用它:
var myDict = (objDict.GetType())objDict; // Assuming this works
var count = myDict.Count; // Get element count
uj5u.com熱心網友回復:
這里的解決方案似乎是強制轉換為 type IDictionary。該類Dictionary<TKey, TValue>實作了該介面,因此無論鍵和值的型別如何,它將提供基本的通用功能。
var handle2 = GCHandle.FromIntPtr(ptrObj);
var myDict = (IDictionary)handle2.Target;
然后,例如,您可以將鍵作為 an 傳遞,然后object將值作為 an 回傳object:
var value = myDict[key];
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510476.html
標籤:C#字典仿制药反射呼唤
