我有一个 DBReader 类,它从多个数据库中读取数据。我有一个 DBDataCache 类,用于缓存特定数据库的数据,并具有成员变量,例如ArrayList arlCostCentres, DataTable dtPriceLists
等。
DBReader 有ReadListOfCostCentres, ReadPriceLists
等方法,它以数据库名称为参数,从数据库中读取数据并返回给调用者。此外,它应该将结果缓存到 DBDataCache 类中。
问题出在 DBReader 的每个方法中,我需要为缓存编写相同的代码行,唯一的区别是我拥有数据的局部变量名称,以及我喜欢的 DBDataCache 类的字段名称存储局部变量。
示例:在 ReadListOfCostCentres 中:
dbData = (DBDataCache) mapDbDataCache[dbName.ToUpper()];
if (dbData == null)
{
dbData = new DBDataCache();
}
dbData.arlCostCentres = arlCostCentres;
在 ReadPriceLists 中:
dbData = (DBDataCache) mapDbDataCache[dbName.ToUpper()];
if (dbData == null)
{
dbData = new DBDataCache();
}
dbData.dtPriceLists = dtPriceLists;
有没有办法避免这种重复编码并使其更通用,或者至少将 4 行代码减少为一行,而不会降低性能?
在 DBDataCache 中,我希望每个重要表都有单独的字段。我不希望使用 key = data name(如“Cost Centers”、“Pricelists”)和 value = ArrayList 或 DataTable 作为值来实现通用的 SortedList。
我希望将重复的代码移到一个单独的函数CacheData
中,但是在 DBDataCache 中设置字段的代码每次都需要一个唯一的字段名称。
有解决办法吗?
谢谢。