从处理抽象类和类型参数固有班 [英] Handling classes inherent from abstract class and type parameter
问题描述
我有一个抽象基类和它的抽象类型参数为:
I have a base abstract class and its abstract type parameter as:
public abstract class Database<T> where T : DatabaseItem, new() {
protected List<T> _items = new List<T> ();
protected virtual void Read (string[] cols) {
T item = new T ();
...
}
public abstract class DatabaseItem {
...
}
然后我有先天的少儿班的人数从它:
Then I have number of children classes inherent from it:
public class ShopDatabase : Database<ShopItem> {}
public class ShopItem : DatabaseItem {}
public class WeaponDatabase : Database<WeaponItem> {}
public class WeaponItem : DatabaseItem {}
...
现在,我想提出一个的词典的跟踪数据库和一个方法来使用回报他们的 DatabaseItem 的类型,像这样:
Now, I want to put a Dictionary to keep track of the databases and a method to return them using DatabaseItem type, something like this:
Dictionary<Type, Database<DatabaseItem>> databases;
public static Database<T> GetDatabase<T> () where T: DatabaseItem {
return databasebases [typeof (T)];
}
然后,它给我的'T'必须是一个非为了使用它作为参数'T'错误的原因的 DatabaseItem 的是抽象的,抽象类型与公共参数构造函数。我做的 DatabaseItem非抽象类型,错误消失的,但仍然很多类型转换错误就出来了...
Then it gave me "'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T'" error because DatabaseItem is abstract. I made DatabaseItem as non-abstract type, the error is gone but still lot of type conversion errors came out...
Found a similar question but I still not understand...
什么是更好的解决方案/结构来实现这一目标?
What's the better solution/structure to achieve this?
推荐答案
你可以做最简单的就是存储数据库< T>
后裔为对象:
The simplest you can do is to store Database<T>
descendants as objects:
static class DatabaseManager
{
private static Dictionary<Type, object> databases = new Dictionary<Type, object>();
// ....
public static Database<T> GetDatabase<T>()
where T : DatabaseItem, new()
{
return (Database<T>)databases[typeof(T)];
}
}
即使你把 DatabaseItem
非抽象类的无参数的构造函数,这将不利于要么,因为的typeof(数据库< ShopItem>)= typeof运算(数据库< DatabaseItem>)!$ C 。$ C>
Even if you turn DatabaseItem
to non-abstract class with parameterless constructor, this won't help either, because typeof(Database<ShopItem>) != typeof(Database<DatabaseItem>)
.
请注意,对于 GetDatabase<泛型约束; T>
方法必须是相同数据库< T>
类
Note, that generic constraints for GetDatabase<T>
method must be the same as for Database<T>
class.
UPD
有没有办法知道一个类使用的是什么类型的参数?例如给
ShopDatabase,我想获得ShopItem。我需要它,当我初始化
数据库字典
is there a way to know what type parameter a class using? e.g. giving ShopDatabase, I want to get ShopItem. I need it when I initialize databases dictionary
使用反射:
var databaseItemType = typeof(ShopDatabase).BaseType.GetGenericArguments()[0];
对于这样的情况:
For cases like this:
class FooDatabase : Database<FooItem> {}
class BooDatabase : FooDatabase {}
// etc...
你需要遍历继承树找到数据库< FooItem方式>
you'll need to loop through inheritance tree to find Database<FooItem>
.
这篇关于从处理抽象类和类型参数固有班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!