This is a follow up to this question...
First, I have this:
public class ListForType<T>
{
private Dictionary<Type, List<T>> listForType
= new Dictionary<Type, List<T>>();
public void AddList(Type type, params T[] list)
{
AddListForType(type, list);
AddListFromSuperiorTypes();
}
public T[] GetList(Type type)
{
return listForType[type].ToArray();
}
private void AddListForType(Type type, T[] list)
{
if (!listForType.ContainsKey(type))
listForType.Add(type, new List<T>());
foreach (T item in list)
AddItemForType(type, item);
}
private void AddItemForType(Type type, T item)
{
if (!listForType[type].Contains(item))
listForType[type].Add(item);
}
private void AddListFromSuperiorTypes()
{
foreach (Type type in listForType.Keys)
foreach (Type typePossibleSuper in listForType.Keys)
if (type.IsSubclassOf(typePossibleSuper))
AddListForType(type, GetList(typePossibleSuper));
}
}
Then I have a sample implementation:
public class Fruit
{
private static ListForType<String> fruitReferenceBooks
= new ListForType<String>();
protected static ListForType<String> FruitReferenceBooks
{
get { return fruitReferenceBooks; }
set { fruitReferenceBooks = value; }
}
static Fruit()
{
FruitReferenceBooks.AddList(typeof(Fruit),
"A Book on Fruit");
}
public String[] ReferenceBooks
{
get { return FruitReferenceBooks.GetList(this.GetType()); }
}
}
public class Banana : Fruit
{
static Banana()
{
FruitReferenceBooks.AddList(typeof(Banana),
"A Book on Bananas");
}
}
public class Apple : Fruit
{
static Apple()
{
FruitReferenceBooks.AddList(typeof(Apple),
"A Book on Apples",
"Another Book on Apples");
}
}
public class McIntosh : Apple
{
static McIntosh()
{
FruitReferenceBooks.AddList(typeof(McIntosh),
"A Book on McIntosh Apples");
}
}
public class GoldenDelicious : Apple
{
static GoldenDelicious()
{
FruitReferenceBooks.AddList(typeof(GoldenDelicious),
"A Book on GoldenDelicious Apples",
"Another Book on GoldenDelicous Apples");
}
}
Along with some test code:
GoldenDelicious gd = new GoldenDelicious();
foreach (String book in gd.ReferenceBooks)
Console.WriteLine(book);
Yielding this:
- A Book on GoldenDelicious Apples
- Another Book on GoldenDelicous Apples
- A Book on Fruit
- A Book on Apples
- Another Book on Apples
What I'm after is a per-class/type-list that's only filled once (via the static constructors) and accessed through an instance-property. The list "inherits" all of the properties from all supertypes (all types in the hiearchy contain the entire list for the hiearchy to make accessing the list as quick as possible).
In the sample implementation I've used the Fruit/Books-on-Fruit to explain what I'm after. (That is - "a book on fruit" is relevant to all fruit, "a book on apples" is only relevant to apples and "a book on a [particular type of apple]" is only applicable to that type of apple.)
So basically my question is - is this a good idea or not? Is there a better way?