这是对this question ...
的跟进首先,我有这个:
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));
}
}
然后我有一个示例实现:
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");
}
}
除了一些测试代码:
GoldenDelicious gd = new GoldenDelicious();
foreach (String book in gd.ReferenceBooks)
Console.WriteLine(book);
产生这个:
我所追求的是每个类/类型列表,它只填充一次(通过静态构造函数)并通过instance-property访问。该列表“继承”所有超类型中的所有属性(层次结构中的所有类型都包含层次结构的完整列表,以便尽快访问列表)。
在示例实现中,我使用Fruit / Books-on-Fruit来解释我的目标。 (也就是说 - “一本关于水果的书”与所有水果有关,“一本关于苹果的书”只与苹果有关,而“一本关于[特定类型的苹果]的书只适用于那种类型的苹果。)
基本上我的问题是 - 这是一个好主意吗?还有更好的方法吗?