重複したコードをメソッドに抽出しないのはなぜですか?
private void Function1()
{
// do function1
}
private void Function2()
{
// do function2
}
private void button1_Click()
{
Function1() ;
if(condition)
{
//...decrement an integer
Function2();
}
}
private void button2_Click()
{
Function1();
if(another condition)
{
//...increment an integer
Function2();
}
}
同じ構造の類似したメソッドが多数ある場合は、作成を検討してください
private void DoSomething(Func<bool> condition, Action action)
{
Function1();
if (condition())
{
action();
Function2();
}
}
そして、次のように呼び出します。
private int value;
private void button2_Click()
{
DoSomething(() => value < 5, () => value++);
}
もちろん、条件やアクションにいくつかのパラメーターを渡す必要がある場合は、変更Func
またはAction
入力する必要があります。また、アクションから何らかの値を返す必要がある場合は、Func
の代わりに使用します。Action
private int value;
private void button2_Click()
{
DoSomething((x) => x % 2 == 0, (x) => x.ToString());
}
private void DoSomething(Func<int, bool> condition, Func<int, string> action)
{
Function1();
if (condition(value))
{
string result = action(value);
Function2();
}
}
条件とアクションがそれほど単純でない場合は、ラムダの代わりに名前付きメソッドを使用してください。
private bool FooCondition(int x)
{
// complex condition here
}
private string BarAction(int x)
{
// complex action here
}
private void button2_Click()
{
DoSomething(FooCondition, BarAction);
}