我有一個狀態機,需要根據我所處的狀態從對象列表中調用每個對象上的不同方法。基本上我試圖重構在每個case語句中有一個循環的代碼狀態機,使其看起來像下面的代碼。但我似乎無法弄清楚如何將相關方法傳遞給我的重構函數(更不用說我不知道如何在每個項目上調用它)在C#中,如何使用Func <T>從另一個類傳遞一個方法?
任何幫助,將不勝感激。
這裏的示例代碼:
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
}
}
}
}
在我看來,這更多的是設計問題而不是'Func'的問題。 –
thekip