有没有办法删除这段代码中的重复项
我有一个如下所示的方法:
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;
}
我有另一个如下所示的方法:
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;
}
有什么方法可以巩固这个,因为唯一不同的是属性名称?
i have a method that looks like this:
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;
}
and i have another method that looks like this:
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;
}
Is there any way to consolidate this as the only thing different is the property names?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个单独的
GetServing
方法:Make a separate
GetServing
method:可以这样使用:
备注:
SomeType
是Servings[0]
的类型,如果我正确理解你的代码,它应该与的类型相同parser.Parse(描述)
。Which could be used like this:
Remark:
SomeType
is the type ofServings[0]
which if I understand your code correctly should be the same as the type ofparser.Parse(Description)
.假设
parser.Parse()
返回与Servings[]
保存的类相同,您可以创建一个 该类型的空对象,X 和Y 为零。然后,您可以有一个函数返回Servings[]
的第一个元素(如果存在),或者返回new FoodDescriptionParser.Parser(Description)
(如果Description
) code> 存在,或者最后是那个空对象。并根据需要收集 X 或 Y。Assuming
parser.Parse()
returns the same class thatServings[]
holds, you could create a null object of that type, for which both X & Y are zero. Then you could have a function that returns the first element ofServings[]
, if it exists, ornew FoodDescriptionParser.Parser(Description)
, ifDescription
exists, or, finally, that null object. And gather the X or Y as needed.