很难准确说出您的意思;根据具体情况,您可以执行以下操作之一:
您可以将构造函数传递给该方法:
public static void fillObject(object [] obs, DataTable dt, Func<object> builder)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
DataRow dr = dt.Rows[j];
if (obs[j] == null)
obs[j] = builder();
fillObject(obs[j], dr);
}
}
或者,如果您知道类型,则可以使用构造函数字典:
Dictionary<Type, Func<object>> sBuilders = new Dictionary<Type, Func<object>>
{
{ typeof(Type1), () => new Type1() },
{ typeof(Type2), () => new Type2() },
// etc...
};
public static void fillObject(object [] obs, DataTable dt, Type pType)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
DataRow dr = dt.Rows[j];
if (obs[j] == null)
obs[j] = sBuilders[pType]();
fillObject(obs[j], dr);
}
}