我创建了一个抽象基类,它是所有其他类的父类。我有另一个数据库连接类,我在那里获取记录,我希望将这些记录转换为类的对象,我将传递给函数。我写的函数就像..
enter code here
//Class AppConnection.cs
public static Dictionary<int, BaseClass> FetchObjects( string sqlQuery, BaseClass obj ) {
DataTable dt = MyConnection.FetchRecords( sqlQuery );
Dictionary<int,BaseClass> objDict = new Dictionary<int, BaseClass>();
for(int i=0; i < dt.Rows.count; i++ ) {
obj.MapObjectByDataRow(dt.Rows[i]); //Abstract function in BaseClass
objDict.Add(obj.Id, obj);
}
return objDict;
}
我在这样的子类中调用它,
enter code here
class Customer:BaseClass
{
public static Dictionary<int, Customer> FetchCustomers() {
string sql = "SELECT * FROM customers";
Dictionary<int, Customer> dict = AppConnection.FetchObjects(sql, new Customer() );
return dict;
}
}
这会导致错误无法隐式转换
enter code here
Dictionary<int,BaseClass> to Dictionary<int,Customer>
答案 0 :(得分:0)
我认为你想要的是通用方法吗?
public static Dictionary<int,T> FetchObjects<T>(string sqlQuery, T obj) where T : BaseClass
{
DataTable dt = MyConnection.FetchRecords( sqlQuery );
Dictionary<int,T> objDict = new Dictionary<int, T>();
for(int i=0; i < dt.Rows.count; i++ ) {
obj.MapObjectByDataRow(dt.Rows[i]); //Abstract function in BaseClass
objDict.Add(obj.Id, obj);
}
return objDict;
}