我有两个完全一样的方法,只是在一条线上 想象一下:
public void ApplyHorizontalScale(int x, int Y)
{
// Code 1
forecast.Formula = Method1(X, Y);
// Code 2
}
public void ApplyVerticalScale(int x, int Y)
{
// Code 1
forecast.Formula = Method2("Foo");
// Code 2
}
int Method1(int x , int y)
{
return x+y;
}
int Method2(string s)
{
return Foo.Length;
}
问题是Code 1和Code 2重复了两次! 我怎么能有这样的东西:
public void ApplyScale(int x, int Y, WhichMethod)
{
// Code 1
forecast.Formula = WhichMethod();
// Code 2
}
请注意,Method1 和 Method2 具有不同的签名,并且其中一个正在访问私有(private)成员。
最佳答案
ApplyVerticalScale 和 ApplyHorizontalScale 是非常好的方法 - 您不需要将它们组合成一个“神” ApplyScale 公共(public)方法。
您应该重构该方法的内部结构,以调用一次包含 Code1 和 Code2 的私有(private) ApplyScale(或类似)方法,每个方法传递在特定方向应用缩放所需的任何内容。
关于c# - 通过传递方法或其他方法删除重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8415049/