2015-05-29 47 views
2

我有一个代码重复,我想避免但我不能创建一个包含代码的方法,因为在一个if中有一个细微的差异。这就是我的意思是:代码重复问题如果

代码1:

If case1() 
{ 
    same code 
    if() 
    { 
     same code 
     line1 
    } 

代码2:

If case2() 
{ 
    same code 
    if() 
    { 
     same code 
     line2 
    } 

两个代码,除了一行(线1和2号线)相同。由于代码很大,我希望能够将其复制到函数中。你有一个想法如何?

感谢

+0

是2号线和一号线的东西,你可以从函数外通? – nvoigt

+0

不,它必须在 – AnasB

回答

1

你可以你的代码分割成多个方法:

if (case1) 
{ 
    subMethod1(); 
    if() 
    { 
     subMethod2(); 
     line1; 
    }  
} 

if (case2) 
{ 
    subMethod1(); 
    if() 
    { 
     subMethod2(); 
     line2; 
    }  
} 
+0

是的我想过,但仍有一些重复,因为我将不得不多次重复使用这两个子方法,因为这部分代码被多次使用。我正在寻求一种解决方案,将所有代码分组,除了一行外。我不知道这是否可能。 – AnasB

3

一般来说,你正在寻找一个ActionFunc。这是一个封装可执行代码的类型:

public int YourCommonMethod(int parameter, Func<int, int> calculate) 
{ 
    // some common code 

    if(calculationNeeded) 
    { 
     // some common code 
     result = calculate(parameter); 
    } 

    // more common code 
} 

然后,您可以用两种不同的计算方法称之为:

int result = YourCommonMethod(5, i => i + 17); 

OR

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); 

OR

int result = YourCommonMethod(5, i => Console.WriteLine("Some string including {0}", i)); 
+0

谢谢我不知道存在,我会尝试它。 – AnasB

+0

由于我的行是一个方法,没有返回任何我使用的行动。你能用相同的实现来帮助我,但采取行动吗?谢谢 – AnasB

+0

@AnasB增加了一个动作实现。如果你的方法没有带参数,你可以使用'Action'而不用''。 – nvoigt