Last active
January 2, 2016 03:19
-
-
Save atrauzzi/8242870 to your computer and use it in GitHub Desktop.
Scratchpad for Stack Overflow question #20907068 http://stackoverflow.com/questions/20907068/how-to-create-a-strongly-typed-collection-that-only-contains-one-element-per-typ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://stackoverflow.com/questions/20907068/how-to-create-a-strongly-typed-collection-that-only-contains-one-element-per-typ | |
class TypedSet<AbstractType> { | |
protected Dictionary<Type, AbstractType> data; | |
public TypedSet() { | |
data = new Dictionary<Type, AbstractType>(); | |
} | |
public void Add(AbstractType subclassOfAbstract) { | |
data.Add(subclassOfAbstract.GetType(), subclassOfAbstract); | |
} | |
public ConcreteType Get<ConcreteType>() where ConcreteType : AbstractType { | |
return (ConcreteType)GetByType(typeof(ConcreteType)); | |
} | |
public bool Has<ConcreteType>() where ConcreteType : AbstractType { | |
return data.ContainsKey(typeof(ConcreteType)); | |
} | |
protected AbstractType GetByType(Type type) { | |
return data[type]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment