C# 4.0 if内部的代码重复问题
我有一个我想要避免的代码重复,但是我不能创建一个包含代码的方法,因为if中的一行中有一点不同。我的意思是: 代码1:C# 4.0 if内部的代码重复问题,c#-4.0,duplication,C# 4.0,Duplication,我有一个我想要避免的代码重复,但是我不能创建一个包含代码的方法,因为if中的一行中有一点不同。我的意思是: 代码1: If case1 () { same code if() { same code line1 } 代码2: If case2 () { same code if() { same code line2 } 除一行(第1行和第2行)外,两个代码相同
If case1 ()
{
same code
if()
{
same code
line1
}
代码2:
If case2 ()
{
same code
if()
{
same code
line2
}
除一行(第1行和第2行)外,两个代码相同。由于代码很大,我希望能够将其复制到函数中。你知道怎么做吗
谢谢您可以将代码拆分为多个方法:
if (case1)
{
subMethod1();
if ()
{
subMethod2();
line1;
}
}
if (case2)
{
subMethod1();
if ()
{
subMethod2();
line2;
}
}
一般来说,您正在查找
操作
或函数
。这是一种封装可执行代码的类型:
public int YourCommonMethod(int parameter, Func<int, int> calculate)
{
// some common code
if(calculationNeeded)
{
// some common code
result = calculate(parameter);
}
// more common code
}
或
就一项行动而言,您需要的更少:
public int YourCommonMethod(int parameter, Action<int> doWork)
{
// some common code
if(calculationNeeded)
{
// some common code
doWork(parameter);
}
// more common code
}
或
第2行和第1行是可以从函数外部传递的吗?不,它一定是内部的。我考虑过这一点,但仍然有一些重复,因为我必须多次重用这两个子方法,因为这部分代码被多次使用。我正在寻找一种解决方案,除了一行代码之外,将所有代码分组。我不知道这是否可能。谢谢你,我不知道存在,我要试试。因为我的行是一个不返回任何内容的方法,所以我使用了一个动作。你能用同样的方法帮我解决问题吗?但要采取行动。Thanks@AnasB添加了一个操作实现。如果您的方法也不使用参数,则可以在不使用
的情况下使用操作。谢谢。非常有帮助!
int result = YourCommonMethod(5, i => i / 48);
public int YourCommonMethod(int parameter, Action<int> doWork)
{
// some common code
if(calculationNeeded)
{
// some common code
doWork(parameter);
}
// more common code
}
int result = YourCommonMethod(5, Console.WriteLine);
int result = YourCommonMethod(5, i => Console.WriteLine("Some string including {0}", i));