現在の状態に応じて、オブジェクトのリストから各オブジェクトで異なるメソッドを呼び出す必要があるステート マシンがあります。基本的には、ステート マシンの各ケース ステートメントにループがあるコードをリファクタリングしようとしています。以下のコードのようになります。ただし、関連するメソッドをリファクタリングされた関数に渡す方法を理解できないようです(言うまでもなく、各アイテムでそれを呼び出す方法がわかりません)
どんな助けでも大歓迎です。
コード例は次のとおりです。
public class MyOtherType
{
public bool Method1()
{ return false; }
public bool Method2()
{ return false; }
public bool Method3()
{ return false; }
public bool Method4()
{ return false; }
}
public class MyType
{
public enum MyState
{
DoSomething1,
DoSomething2,
DoSomething3,
DoSomething4
}
private MyState State = MyState.DoSomething1;
List<MyOtherType> MyListOfObjects = new List<MyOtherType>() { new MyOtherType(), new MyOtherType() };
private void StateMachine()
{
switch (State)
{
case MyState.DoSomething1:
//How do I pass this in? Do I need to set it up differnetly?
Process(() => MyOtherType.Method1());
break;
case MyState.DoSomething2:
Process(() => MyOtherType.Method2);
break;
case MyState.DoSomething3:
Process(() => MyOtherType.Method3);
break;
case MyState.DoSomething4:
Process(() => MyOtherType.Method4);
break;
}
}
private void Process(Func<bool> method)
{
foreach (MyOtherType item in MyListOfObjects)
{
//How do I call the method on each item?
if (item.method())
{
//Do something
}
}
}
}