سؤال

First of all, this is my first question here, so let me know if I'm doing anything wrong.

I'm working on a couple of somewhat complicated C# scripts for Unity, and currently I need a Dictionary mapping from pointers of unknown types to object instances of types depending on the type of the key pointer:

(void* => MyClass<T>)

where T is the type of the target of the key pointer for each entry.

Firstly, how should I specify the key type? void* doesn't seem to be valid.

Secondly, is there an elegant way to specify the type bound? Otherwise I can probably improvise a solution.

هل كانت مفيدة؟

المحلول

As you've already discovered pointer types in C# can't be used as the key type of a Dictionary<TKey, TValue>. A IntPtr value can though and every void* is convertible to IntPtr. Hence I would use Dictionary<IntPtr, MyClass<T>> and just map the void* values into IntPtr.

unsafe class Container<T> { 
  Dictionary<IntPtr, MyClass<T>> m_map;
  void Add(void* key, MyClass<T> value) { 
    IntPtr ptr = (IntPtr)key;
    m_map.Add(ptr, value);
  }

  bool TryGetValue(void* key, out MyClass<T> value) { 
    IntPtr ptr = (IntPtr)key;
    return m_map.TryGetValue(ptr, out value);
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top