【发布时间】:2013-04-25 04:46:36
【问题描述】:
我试图找到重构代码的方法,但不知道该怎么做。
例如,我们有几个类
class A {
string name;
int year;
}
class B {
long id;
string code;
DateTime currentTime;
}
class C {
string lastname;
DateTime currentDate;
}
然后我需要返回这些类 List、List、List 的对象列表并将它们转换为 Object[][]。
对于每次转化我都做同样的事情
private Object[][] converAListToObjectArray(List<A> dataList)
{
long countRecords = dataList.Count();
const int countProperty = 2;
var arrayRes = new object[countRecords][];
for (int i = 0; i < countRecords; i++)
{
var arrayObjProperty = new object[countProperty];
arrayObjProperty[0] = dataList[i].Name;
arrayObjProperty[1] = dataList[i].Year;
arrayRes[i] = arrayObjProperty;
}
return arrayRes;
}
private Object[][] converBListToObjectArray(List<B> dataList)
{
long countRecords = dataList.Count();
const int countProperty = 3;
var arrayRes = new object[countRecords][];
for (int i = 0; i < countRecords; i++)
{
var arrayObjProperty = new object[countProperty];
arrayObjProperty[0] = dataList[i].Id;
arrayObjProperty[1] = dataList[i].Code;
arrayObjProperty[2] = dataList[i].CurrentTime;
arrayRes[i] = arrayObjProperty;
}
return arrayRes;
}
是否可以使用某种设计模式来分离这种转换?
【问题讨论】:
-
不清楚你想在这里完成什么..你想得到一个通用的,将列表转换为二维数组函数吗?
-
@Sayse 我尝试创建将任何对象列表转换为二维数组的统一函数
-
你为什么要这样做?
-
不过,这确实是一件很奇怪的事情。你在什么情况下以这种方式穿梭于物体周围?为什么泛型在这里不起作用?
-
如果这真的只适用于 Excel,并且您使用的是 Excel 2007 或更高版本,请阅读Office Open XML Formats: Inserting Values into Excel 2007 Cells
标签: c# design-patterns refactoring template-method-pattern