我有.net 3.5,我想做一个通用的方法。我该如何重构此代码?
case (int)Enums.SandwichesHoagies.Cheeses:
if (this.Cheeses.Where(x => x.Id == product.ProductId).SingleOrDefault() == null)
{
var newCheese = new Cheese
{
Id = product.ProductId,
Name = product.Name,
PriceValue = product.Price.HasValue ? (double)product.Price.Value : 0.00
};
this.Cheeses.Add(newCheese);
}
else
{
foreach (var cheese in this.Cheeses.Where(cheese => cheese.Id == product.ProductId))
{
this.Cheeses.Remove(cheese);
break;
}
}
foreach (var cheese in Cheeses) cheese.Type = string.Empty;
if (this.Cheeses.Count > 0) Cheeses.First().Type = "Cheeses:";
break;
case (int)Enums.SandwichesHoagies.Meats:
if (this.Meats.Where(x => x.Id == product.ProductId).SingleOrDefault() == null)
{
var newMeat = new Meat
{
Id = product.ProductId,
Name = product.Name,
PriceValue = product.Price.HasValue ? (double)product.Price.Value : 0.00
};
this.Meats.Add(newMeat);
}
else
{
foreach (var meat in this.Meats.Where(meat => meat.Id == product.ProductId))
{
this.Meats.Remove(meat);
break;
}
}
foreach (var meat in Meats) meat.Type = string.Empty;
if (this.Meats.Count > 0) Meats.First().Type = "Meats:";
break;
最佳答案
假设两件事:Meat
和Cheese
继承自Ingredient
或实现IIngredient
Meats
和Cheeses
集合是IList<T>
开始了:
private void OuterMethod()
{
switch(something)
{
case (int)Enums.SandwichesHoagies.Cheeses:
HandleCase(product, this.Cheeses);
break;
case (int)Enums.SandwichesHoagies.Meats:
HandleCase(product, this.Meats);
break;
}
}
private void HandleCase<T>(Product product, List<T> list) where T : Ingredient, new()
{
if(list.Any(i => i.Id == product.ProductId))
{
list.Add(new T {
Id = product.ProductId,
Name = product.Name,
PriceValue = product.PriceValue ?? 0.0;
});
}
else
{
list.RemoveAll(i => i.Id == product.ProductId);
}
//NOTE: this part seems like a bad idea. looks like code smell.
foreach (var i in list)
{
i.Type = string.Empty;
}
if (list.Count > 0)
{
list.First().Type = "Cheeses:";
}
}
关于c# - 我该如何重构此代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4588604/