我创建了一个库函数,并希望添加一个重载,它使用附加参数执行非常相似的操作。现有代码如下所示:
public class MealsAllocation
{
public int mealId;
public List<CrewSummary> crew;
private MealsAllocation() { }
public MealsAllocation(int MealId) {
mealId = MealId;
string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
//first fill an ienumerable redemption object for the meal
List<MealRedemption> mealRedemptions = new List<MealRedemption>();
SqlCommand cmdRed = new SqlCommand("tegsGetMealsRedemption", conn);
cmdRed.CommandType = CommandType.StoredProcedure;
cmdRed.Parameters.Add(new SqlParameter("@mealId", MealId));
conn.Open();
SqlDataReader drRed = cmdRed.ExecuteReader();
while (drRed.Read())
{
MealRedemption mr = new MealRedemption(Convert.ToInt32(drRed["crewId"]), Convert.ToDateTime(drRed["creation"]), Convert.ToInt32(drRed["redeemed"]));
mealRedemptions.Add(mr);
}
conn.Close();
//then fill the crew list
crew = new List<CrewSummary>();
SqlCommand cmdCrew = new SqlCommand("tegsGetMealsAllocation", conn);
cmdCrew.CommandType = CommandType.StoredProcedure;
cmdCrew.Parameters.Add(new SqlParameter("@mealId", MealId));
conn.Open();
SqlDataReader drCrew = cmdCrew.ExecuteReader();
while (drCrew.Read())
{
int drCid = Convert.ToInt32(drCrew["id"]);
List<MealRedemption> drMr = mealRedemptions.FindAll(red => red.crewId == drCid) ;
CrewSummary cs = new CrewSummary(drCid, Convert.ToInt32(drCrew["allocation"]), drMr );
crew.Add(cs);
}
conn.Close();
}
那么现在我想添加一个新的重载,看起来有点像这样:
public MealsAllocation(int MealId, int crewId)
{
}
本质上,这将与上述内容大致相同但略有不同。
避免“复制和粘贴继承”的好策略是什么?即重构上述内容的好方法,使其更容易承受重载?