gpt4 book ai didi

c# - 通过传递方法或其他方法删除重复代码?

转载 作者:行者123 更新时间:2023-11-30 19:19:43 25 4
gpt4 key购买 nike

我有两个完全一样的方法,只是在一条线上想象一下:

    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 和 ApplyHorizo​​ntalScale 是非常好的方法 - 您不需要将它们组合成一个“神” ApplyScale 公共(public)方法。

您应该重构该方法的内部结构,以调用一次包含 Code1 和 Code2 的私有(private) ApplyScale(或类似)方法,每个方法传递在特定方向应用缩放所需的任何内容。

关于c# - 通过传递方法或其他方法删除重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8415049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com