我努力解决围绕数据表类而不是消息的类似问题。上面提到的将类的非泛型版本转换为派生的泛型版本的根本问题是相同的。
为了允许注入到不支持数据库的可移植类库中,我引入了一组接口类,目的是我可以传递一个类型并获得一个匹配的泛型。它最终需要实现一个泛型方法。
// Interface for injection
public interface IDatabase
{
// Original, non-functional signature:
IDatatable<object> GetDataTable(Type dataType);
// Functional method using a generic method:
IDatatable<T> GetDataTable<T>();
}
这是使用上述通用方法的整个实现。
将从字典中强制转换的泛型类。
// Non-generic base class allows listing tables together
abstract class Datatable
{
Datatable(Type storedClass)
{
StoredClass = storedClass;
}
Type StoredClass { get; private set; }
}
// Generic inheriting class
abstract class Datatable<T>: Datatable, IDatatable<T>
{
protected Datatable()
:base(typeof(T))
{
}
}
这是存储泛型类并对其进行强制转换以满足接口中的泛型方法的类
class Database
{
// Dictionary storing the classes using the non-generic base class
private Dictionary<Type, Datatable> _tableDictionary;
protected Database(List<Datatable> tables)
{
_tableDictionary = new Dictionary<Type, Datatable>();
foreach (var table in tables)
{
_tableDictionary.Add(table.StoredClass, table);
}
}
// Interface implementation, casts the generic
public IDatatable<T> GetDataTable<T>()
{
Datatable table = null;
_tableDictionary.TryGetValue(typeof(T), out table);
return table as IDatatable<T>;
}
}
最后是接口方法的调用。
IDatatable<CustomerAccount> table = _database.GetDataTable<CustomerAccount>();