Reputation: 818
I want to make a Dictionary that has a type of a class and a stack. The type of a class will be the key for the dictionary.
private Dictionary<typeof(Enemy), Stack> d;
The line above, of course, won't compile.
Enemy classes involved:
public abstract Enemy : MonoBehaviour {}
public class A : Enemy {}
public class B : Enemy {}
I am building up on my previous question: Dictionary to Stack Class Types Together (no need to read it unless you really want to).
So how do I use my class type as the key in the dictionary? I rather not use String names or enums.
Dictionary should look like this in memory:
[A] --> stack[]
[B] --> stack[]
That is, every Enemy type gets a stack.
Upvotes: 0
Views: 65
Reputation: 39447
Are you trying to define some dictionary
<K,V>
where K is any object of a class which is a subclass of Enemy? Or ... where K is any Type which subclasses Enemy?
I've thought on this myself on a few occasions.
So... I am not quite familiar with the newest C# language features. I would probably just define it as
<Type, V>
then as things are added to this structure make a check myself if the type tp added actually IsSubclassOf the Enemy type, and if not I would throw an exception.
But there might be a better way using the newest C# language features.
Upvotes: 0
Reputation: 842
Are you looking for something like:
var dictionary = new Dictionary<Type,Stack>();
Usage would be:
dictionary.Add(typeof(A),new Stack());
dictionary.Add(typeof(B),new Stack());
dictionary[typeof(A)].Push(new Object());
var objectFromStackOfA = dictionary[typeof(A)].Pop();
Upvotes: 2
Reputation: 444
Simple solution is to use string as a type of your class:
override the ToString() method of your classes, then use it to add in the dictionary!
public class Enemy { }
public class A : Enemy
{
public override string ToString()
{
return "A";
}
}
public class B : Enemy
{
public override string ToString()
{
return "B";
}
}
public class Stack { }
class Program
{
static void Main(string[] args)
{
Dictionary<string, Stack> d = new Dictionary<string, Stack>();
A obj1 = new A();
A obj2 = new A();
B obj3 = new B();
B obj4 = new B();
d.Add(obj1.ToString(), new Stack());
d.Add(obj2.ToString(), new Stack());
d.Add(obj3.ToString(), new Stack());
d.Add(obj4.ToString(), new Stack());
}
}
Upvotes: 0