leo*_*ora 5 .net c# code-duplication .net-3.5
我有一个看起来像这样的方法:
private double GetX()
{
if (Servings.Count > 0)
{
return Servings[0].X;
}
if (!string.IsNullOrEmpty(Description))
{
FoodDescriptionParser parser = new FoodDescriptionParser();
return parser.Parse(Description).X;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我有另一个看起来像这样的方法:
private double GetY()
{
if (Servings.Count > 0)
{
return Servings[0].Y;
}
if (!string.IsNullOrEmpty(Description))
{
FoodDescriptionParser parser = new FoodDescriptionParser();
return parser.Parse(Description).Y;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法巩固这个,因为唯一不同的是属性名称?
SLa*_*aks 12
制作一个单独的GetServing方法:
private Serving GetServing() {
if (Servings.Count > 0)
return Servings[0];
if (!string.IsNullOrEmpty(Description)) {
FoodDescriptionParser parser = new FoodDescriptionParser();
return parser.Parse(Description);
}
return null;
}
private double GetX() {
Serving serving = GetServing();
if (serving == null) return 0;
return serving.X;
}
private double GetY() {
Serving serving = GetServing();
if (serving == null) return 0;
return serving.Y;
}
Run Code Online (Sandbox Code Playgroud)
private double Get(Func<SomeType, double> valueProvider)
{
if (Servings.Count > 0)
{
return valueProvider(Servings[0]);
}
if (!string.IsNullOrEmpty(Description))
{
FoodDescriptionParser parser = new FoodDescriptionParser();
return valueProvider(parser.Parse(Description));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
哪个可以这样使用:
var x = Get(value => value.X);
var y = Get(value => value.Y);
Run Code Online (Sandbox Code Playgroud)
备注:如果我理解你的代码正确应该与类型相同,SomeType是Servings[0]哪种类型parser.Parse(Description).